Giving The Script Tag an Id

Giving the script tag an ID

It's fine in all current browsers.

The only browser that got <script id> wrong was Netscape 4, which we stopped caring about a long, long time ago.

That quirksmode page seems to be badly out of date, what with its use of language attributes, script <!-- hiding, and application/x-javascript. Its advice about avoiding <script> in the <body> (and putting it in <head> instead) is at odds with today's encouraged practices.

If we're talking <script> attribute compatibility problems: defer doesn't work everywhere so don't rely on it; charset doesn't work everywhere, and neither does the charset parameter on the served script's Content-Type, so your script charset had better match the page; type should always be text/javascript and not one of the non-working alternatives the pedants who wrote RFC 4329 would like you to use.

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

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...

Why would I put an ID on a script tag?

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.

Script tags with IDs?

HTML 4 Answer:

No, you can't, at least not if you want valid HTML...

The following elements can't have an ID attribute:

  • <base>
  • <head>
  • <html>
  • <meta>
  • <script>
  • <style>
  • <title>

There might be a couple more.

This is confusing because viewing just the documentation for the ID/class attributes doesn't specifically say that they can't be used with these elements. You have to look at the DTD for the elements to see that the general attributes are not defined for the element, and thus cannot be used.


HTML 5 Answer:

The default document type declaration, HTMLElement, which applies to all elements in HTML specifies that these global attributes (including the ID attribute) can be used on any element you create, so it would appear you can do this in HTML 5, but not in HTML 4.

How to Change <script> id from with script - Javascript

Use setAttribute

script.setAttribute("id", script.id + "_" + sessionID);

Is it possible to refer to function or object from particular script tag in HTML file

Yes this is totally possible, but you should use a type other than text/javascript.

<script id='tag-1' type="myScriptHolder">
function foo(){
alert("this is foo-1");
}
</script>

<script id='tag-2' type="myScriptHolder">
function foo(){
alert("this is foo-2");
}
</script>

<script id='tag-3' type="myScriptHolder">
function foo(){
alert("this is foo-3");
}
</script>

<script>
$.globalEval($('#tag-1').text();
</script>

custom attributes in a script tag

Yes, you can do this. Browsers are required to ignore attributes they don't recognize in any tag (to allow for graceful degradation when a document uses new features with an old browser).
However, it would be better to use a dataset tag, since these are explicitly reserved for users, so they don't conflict with future HTML changes.

<script id="myscript" type="text/javascript" data-mycustomattribute="foo">

You can then access this either using an ordinary attribute accessor:

document.getElementById("myscript").getAttribute("mycustomattribute")

or with the dataset API:

document.getElementById("myscript").dataset.mycustomattribute

(but see the browser compatibility table in the documentation).

Where should I put <script> tags in HTML markup?

Here's what happens when a browser loads a website with a <script> tag on it:

  1. Fetch the HTML page (e.g. index.html)
  2. Begin parsing the HTML
  3. The parser encounters a <script> tag referencing an external script file.
  4. The browser requests the script file. Meanwhile, the parser blocks and stops parsing the other HTML on your page.
  5. After some time the script is downloaded and subsequently executed.
  6. The parser continues parsing the rest of the HTML document.

Step #4 causes a bad user experience. Your website basically stops loading until you've downloaded all scripts. If there's one thing that users hate it's waiting for a website to load.

Why does this even happen?

Any script can insert its own HTML via document.write() or other DOM manipulations. This implies that the parser has to wait until the script has been downloaded and executed before it can safely parse the rest of the document. After all, the script could have inserted its own HTML in the document.

However, most JavaScript developers no longer manipulate the DOM while the document is loading. Instead, they wait until the document has been loaded before modifying it. For example:

<!-- index.html -->
<html>
<head>
<title>My Page</title>
<script src="my-script.js"></script>
</head>
<body>
<div id="user-greeting">Welcome back, user</div>
</body>
</html>

JavaScript:

// my-script.js
document.addEventListener("DOMContentLoaded", function() {
// this function runs when the DOM is ready, i.e. when the document has been parsed
document.getElementById("user-greeting").textContent = "Welcome back, Bart";
});

Because your browser does not know my-script.js isn't going to modify the document until it has been downloaded and executed, the parser stops parsing.

Antiquated recommendation

The old approach to solving this problem was to put <script> tags at the bottom of your <body>, because this ensures the parser isn't blocked until the very end.

This approach has its own problem: the browser cannot start downloading the scripts until the entire document is parsed. For larger websites with large scripts and stylesheets, being able to download the script as soon as possible is very important for performance. If your website doesn't load within 2 seconds, people will go to another website.

In an optimal solution, the browser would start downloading your scripts as soon as possible, while at the same time parsing the rest of your document.

The modern approach

Today, browsers support the async and defer attributes on scripts. These attributes tell the browser it's safe to continue parsing while the scripts are being downloaded.

async

<script src="path/to/script1.js" async></script>
<script src="path/to/script2.js" async></script>

Scripts with the async attribute are executed asynchronously. This means the script is executed as soon as it's downloaded, without blocking the browser in the meantime.
This implies that it's possible that script 2 is downloaded and executed before script 1.

According to http://caniuse.com/#feat=script-async, 97.78% of all browsers support this.

defer

<script src="path/to/script1.js" defer></script>
<script src="path/to/script2.js" defer></script>

Scripts with the defer attribute are executed in order (i.e. first script 1, then script 2). This also does not block the browser.

Unlike async scripts, defer scripts are only executed after the entire document has been loaded.

(To learn more and see some really helpful visual representations of the differences between async, defer and normal scripts check the first two links at the references section of this answer)

Conclusion

The current state-of-the-art is to put scripts in the <head> tag and use the async or defer attributes. This allows your scripts to be downloaded ASAP without blocking your browser.

The good thing is that your website should still load correctly on the 2% of browsers that do not support these attributes while speeding up the other 98%.

References

  • async vs defer attributes
  • Efficiently load JavaScript with defer and async
  • Remove Render-Blocking JavaScript
  • Async, Defer, Modules: A Visual Cheatsheet

Why my code doesn't work when the script tag is in the head tag?

First, the HTML get parsed from top to bottom, So Whatever encounter first will get run.

If you put script tag at the end of the head tag then It will run first before the HTML body so you can't set width because when you used

document.getElementById("video")

It would return null so you can't set properties on null. Because at the time of this statement the element doesn't exist.

<html>

<head>
<script>
const heading = document.querySelector("h1");
console.log(heading); // null
</script>
</head>

<body>
<h1> This is heading</h1>
</body>

</html>


Related Topics



Leave a reply



Submit