Saturday, August 18, 2018

javascript - HTML5: Why a script tag needs to be placed at the end of body tag instead at the beginning of the body tag?





While writing a html , some sites recommend to write the script at the end of the BODY tag instead of writing at the beginning of BODY tag and i read this will increase the performance of page refresh , But How does this helping when html page is rendered only after DOM parses all the tags ?


Answer



javascript loading isn't part of the DOM, but it's blocking and it will interrupt the loading process until it's done. Even if it's a small script, it's still an extra request and will slow down the whole process.



Truth is browsers only need the DOM structure to start rendering, they don't need the scripts nor do they count for layout purposes. They are just dead weight until they are executed.



Even CSS could be considered unnecesary for the initial rendering process (more or less), but since CSS loading is non-blocking, this isn't an issue.



The performance gain from putting scripts at the bottom can vary, and even if it's a reccomended practice it might not always be harmless. When dealing with CMSs, for example, you might design your theme to load the scripts at the bottom, but you have no control over plugins. This happens a lot with wordpress, for example, and people end up putting script in the head to avoid conflicts with plugins.




Bonus Track (a few years later)



When in comes to tracking scripts, such as mixpanel, inspectlet, even google analytics... you might want to detect when a user enters your page and leaves a few seconds later due to slow loading times, an adult advertising block... whatever.



If you put the tracking script and the bottom it might not be able to boot in time to detect that visit, so you won't know you have such extreme bounce rate. In this case I'd consider putting the script in the head.



If you put resource hints at the beggining, say








Or






It would mitigate the drawback of loading said scripts in the head.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...