Reputation: 4853
I have read in the docs of some third party providers (e.g. adsense) that their script must go in the <head>
.
For async
scripts I'm fairly sure this is untrue since the async flag doesn't guarantee anything about when the script will be executed. But I'm curious about non-async scripts too. Does it makes sense to say that a script tag must go in the <head>
?
(This is assuming that there isn't any code in the page that relies upon some script having loaded).
To be clear, my question isn't "is it a good idea", or "what are the performance benefits".
It's more like: "is it technically possible that a script could NOT work, because it isn't in the <head>
?"
Thanks!
Upvotes: 1
Views: 159
Reputation: 655
A tag can be placed anywhere in the html page, But placing in the tag will slow down the creation of DOM elements in the browser, because browser needs to get all the script tags and move to html elements,
The best practice is to keep the script tag at the bottom of DOM elements, because the visual html elements will be loaded before the script js getting load.
It mainly depends on the functionality of the script and the business logic of the page.
Upvotes: 0
Reputation: 916
The MDN page on the script tag does not place any requirements on the location of a script tag. In fact it seems that the modern trend is now to put scripts at the very end of the body.
Upvotes: 0
Reputation:
A <script></script>
in the <head>
tag will stop the DOM from parsing until the script has loaded. Put scripts here that need to be loaded before the DOM is parsed. Don't put any unnecessary scripts here, as it stops the DOM from parsing. That results in a slow-to-load page.
See: https://stackoverflow.com/a/24070373/47589
Upvotes: 2