Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the point of using an ID attribute in a script tag?

Basically what I am asking is what is the point of giving my script tags an id attribute? Can the routines inside of them be called or referenced differently because of this identification? Could this cause any problems making the script/page act funny?

like image 765
John Avatar asked Aug 14 '12 20:08

John


3 Answers

The id is just another accessor of the <script> tag inside the DOM tree. You could in theory use document.getElementById() to retrieve the <script> node and delete it or add other attributes (though I don't believe you can modify the src attribute once it has loaded in the DOM). The id isn't required for those operations though -- it could have been accessed by any DOM function such as getElementsByTagName("script") as well.

If you do need to access the <script> tag with DOM manipulations, the id makes it just a little easier. Otherwise, there is little benefit1.


1That is sort of true of adding an id attribute to any DOM node, though nodes affecting presentation can also benefit from CSS targeting the id, unlike a <script> tag...

like image 66
Michael Berkowski Avatar answered Oct 24 '22 08:10

Michael Berkowski


As the earlier answers have mentioned, once the code in the script tag runs, it's results will not be undo-ed by replacing/deleting the script node.

But the id can be useful if the code has not run till now. Following is such a script tag:

<script id="code1" type="text/myjs">.....</script>

Since the browser is not aware of this type of script, it will ignore it's execution but the tag and it's code will still be available in the DOM.

Working example: http://jsfiddle.net/sv_in/rt9Q2/

This is largely used for client side templates. A template, example for Mustache.js, is stored in such a script tag. When it is needed to be compiled, it is obtained from tag using it's id. Advantage with this approach is that the view (templates) and the model (js variable which contain data to be shown in the view) is completely separate.

Other than this practise, there is no general purpose use for an id for a script tag

like image 39
sv_in Avatar answered Oct 24 '22 08:10

sv_in


There is no meaning giving id to your script tags, the scripts on a page just execute in a sequence they are on the page.

like image 1
Taha Rehman Siddiqui Avatar answered Oct 24 '22 07:10

Taha Rehman Siddiqui