I have a <script> where it adds to the <head> another script.
This new script is supposed to find the original <script> that inserted it.
can I put <script id="blablabla"> and let the new <script> find it?
<div id="placeholder-1"></div>
<script type="text/javascript">
<//![CDATA[
(function() {
var s = document.createElement("script");
s.type = "text/javascript";
s.async = true;
s.src = "blablabla.com/blabla.js";
(document.getElementsByTagName("head")[0] ||
document.getElementsByTagName("body")[0]).appendChild(s);
})();//]]></script>
Now, the blabla.js needs to find the div placeholder.
I am trying to save that div placeholder, by giving it’s id already to the script.
is that a browser compatible?
thanks
In HTML 5, just place an
idattribute on thescripttag.In HTML 4, the id tag isn’t actually defined as being valid on a script tag.
http://www.w3.org/TR/html4/interact/scripts.html#edef-SCRIPT Official W3C Specification
Only src, type, langugage, defer and charset are officially allowed.
A valid work around would be this…
You can now traverse to the script using the id of the div element in your “blabla.js”
So essentially, by nesting the script inside of an element with an id, we can get to the script from another script and also have valid markup.
Additional note: in the HTML 4 spec, id was genuinely not allowed on the script tag: