Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would I put an ID on a script tag?

Tags:

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?

like image 429
Xavi Avatar asked Aug 02 '09 21:08

Xavi


People also ask

What does id mean in JavaScript?

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.

What are script tags for?

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.

Where is the correct place to put the script tag?

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.

What is id and class in HTML?

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.


3 Answers

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.

like image 102
Paolo Bergantino Avatar answered Jan 18 '23 03:01

Paolo Bergantino


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.

like image 22
Darko Z Avatar answered Jan 18 '23 04:01

Darko Z


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

like image 45
niutech Avatar answered Jan 18 '23 05:01

niutech