views:

57

answers:

2

Hi

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

A: 

Yes, you can do it. id is one of the global attributes and those may be specified on all HTML elements (even those not defined in html specification). The tag script itself has allowed

Content attributes:
Global attributes
src
async
defer
type
charset

EDIT

Note, that this information is taken from the HTML5 spec. I am not sure of the previous versions, which might still be used in tutorials.

As such, it should be already browser compatible with all major browsers (ie those claiming to support HTML5).

Trimack
so why they write it isnt? http://www.w3schools.com/tags/tag_script.asp
oshafran
by reading http://www.w3schools.com/tags/ref_standardattributes.asp, I found that script and some other tags did not support `id`, `class`, `style`, etc. BUT I do tried adding `id` to a script tag and I can locate it by using $("#script_id") in jQuery.
PeterWong
oshafran
Note that technically this is only true of HTML5. Previous HTML specs explicitly did not allow the `id` attribute on `script` tags. I suspect most browsers would render it fine in an HTML 4 document — it would just be invalid — though it would kill rendering for XHTML 1.1 documents.
Chuck
A: 

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...

<div id="scriptcontainer">
     <script type="text/javascript">
         // Your script here
     </script>
</div>

You can now traverse to the script using the id of the div element in your "blabla.js"

var myScript = document.getElementById("scriptcontainer").getElementsByTagName("script");

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.

Sohnee