I've recently read the Yahoo manifesto Best Practices for Speeding Up Your Web Site. They recommend to put the JavaScript inclusion at the bottom of the HTML code when we can.
But where exactly and when?
Should we put it before closing </html>
or after ? And above all, when should we still put it in the <head>
section?
JavaScript in <head> or <body> 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.
The best practice is to put JavaScript <script> tags just before the closing </body> tag rather than in the <head> section of your HTML. The reason for this is that HTML loads from top to bottom. The head loads first, then the body, and then everything inside the body.
By placing the JS at the bottom of your page before the closing </body> tag, you are allowing the HTML to be parsed prior to loading the javascript. This gives the effect of faster page load times.
There are two possibilities for truly unobtrusive scripts:
</body></html>
)The second one can be faster as the original Yahoo research showed some browsers try to load script files when they hit the script tag and therefore don't load the rest of the page until they have finished. However, if your script has a 'ready' portion which must execute as soon as the DOM is ready you may need to have it in the head. Another issue is layout - if your script is going to change the page layout you want it loaded as early as possible so your page does not spend a long time redrawing itself in front of your users.
If the external script site is on another domain (like external widgets) it may be worth putting it at the bottom to avoid it delaying loading of the page.
And for any performance issues do your own benchmarks - what may be true at one time when a study is done might change with your own local setup or changes in browsers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With