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?
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...
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With