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?
The id attribute specifies a unique id for an HTML element. The value of the id attribute must be unique within the HTML document. The id attribute is used to point to a specific style declaration in a style sheet. It is also used by JavaScript to access and manipulate the element with the specific id.
Definition and Usage. The <script> tag is used to embed a client-side script (JavaScript). The <script> element either contains scripting statements, or it points to an external script file through the src attribute. Common uses for JavaScript are image manipulation, form validation, and dynamic changes of content.
You can place any number of scripts in an HTML document. Scripts can be placed in the <body> , or in the <head> section of an HTML page, or in both.
In Html for an element ID name starts with the “#” symbol followed by a unique name assigned to it. On the other hand class assigned to an element has its name starts with “.” followed by class name. 2. Selector. Only one ID selector can be attached to an element.
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.
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.
The benefit is that you can refer to the element with an id="foo"
using the global variable window.foo
or just foo
:
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