Under what circumstances can the location of script tag be in the head tag of HTML?

is at the front end of learning recently. A common problem is where to put script tag in HTML.

there is an example that, HTML markups is like this

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
    <script src="js.js">
    </script>
  </head>
  <body>
  </body>
</html>

JS file is like this

var loadTime = document.createElement("div");
loadTime.textContent = "You loaded this page on: " + new Date();
loadTime.style.color = "blue";
document.body.appendChild(loadTime);

I initially thought that this JS did not depend on any DOM elements in the current HTML, so the effect would be the same anywhere I put it in the HTML. But after running, it is found that it is not possible to put it in head, and it has to be put in front of body closing tag.

this makes me wonder, if such script can not be put in head, then what kind of script can be put in head?

in addition, I know that script tag now has two attribute async and defer that allow browsers to render HTML without blocking when they encounter script. And http://caniuse.com/-sharpfeat=scri. says that 94.59% of browsers now support this attr. But I looked around the Internet and never saw a website that used this attr.

Mar.28,2021

but after running it, it is found that it is not possible to put it in head

I tested it, and it was fine, but the js code must be placed in a .js file, not directly in head.

but I've looked around on the Internet, and I've never seen a website that has ever used this attr
.

you can see the compatibility of a browser. It is not supported below IE11, and there is no great need to use this attribute. Just put js at the end, so why do you have to put it in head?


at first I didn't think that this JS depended on any DOM elements in the current HTML

this sentence is not true.

document.body.appendChild (loadTime); here depends on body .

output document.body in head , and you will get null .


js can be placed anywhere in the document, which has nothing to do with the document structure itself. If you don't believe it, just play alert and pop up a certain number, and you can verify it!


if you have some dom operations in your js, put them below normally so as not to affect the rendering speed of html pages.

Menu