[ACCEPTED]-Why would I put an ID on a script tag?-html

Accepted answer
Score: 16

The one use I've seen of this is if you 8 want to provide widget for customers and 7 you instruct them to place the <script> tag wherever 6 they want the widget to show up. If you 5 give the <script> element an ID then you can reference 4 that inside of it to place the code in the 3 right place. That's not to say that it is 2 the only way of achieving that, of course, but 1 I've seen it done and suggested it in the past.

Score: 6

I've seen it used for Microtemplating, where 4 you can put a template in a script tag and 3 then reference it through the ID.

Here's great post with javascript microtemplating by John Resig - note 2 that this is not the ONLY way of achieving 1 this, only Johns version of it.

Score: 3

The benefit is that you can refer to the 2 element with an id="foo" using the global variable 1 window.foo or just foo:

id as a global variable

Score: 1

By using an ID, you can wait on the specific 2 JS file to finish loading. FB does this

(function(d, s, id){
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)){ return; }
    js = d.createElement(s); js.id = id;
    js.onload = function(){
        // remote script has loaded
    js.src = "//connect.facebook.net/en_US/sdk.js";
    fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

facebook-jssdk 1 being their unique identifier.


More Related questions