24

I've noticed that some web developers put IDs on scripts tags. For example:

<script id="scripty" src="something.js" type="text/javascript"></script>

I know that according the W3C this is perfectly legal markup, but what's the benefits of doing this?

Xavi
  • 20,111
  • 14
  • 72
  • 63

4 Answers4

16

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

Community
  • 1
  • 1
Paolo Bergantino
  • 480,997
  • 81
  • 517
  • 436
6

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

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

Darko
  • 38,310
  • 15
  • 80
  • 107
3

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

id as a global variable

niutech
  • 28,923
  • 15
  • 96
  • 106
1

By using an ID, you can wait on the specific 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 being their unique identifier.

[https://stackoverflow.com/a/8578840][1]

ladder
  • 189
  • 2
  • 9