The ways of loading JavaScript files onto your page
Varios ways to load the script on the page and boos performances
Recently I was working on speeding up my website. As a reference I user Google PageSpeed Insights.
There were few things, but among them was one that was that really poked my eyes. It was the one regarding blocking scripts
After some time spent googling and reading insight recommendation I got to the script loading and executing order on the modern browsers.
It turns out that there are options of how to and when to load script according to the page load flow. I focused only on techniques applicable for modern browsers, so no IE6 support :)
Apparently there are three possible ways to load the script regardless of the position of script tags. Basically it is not such a big deal where you place your script tags anymore. You can place them in a head or at the end f the body and still make them load and execute when you want.
So, about those three ways to load a script. There is an optimal attribute you can use in your script tag depending when you want to load and execute your script.
None - no attribute <script>
This means that the page will load scripts when the parser reaches script tag. This means pause page processing until script is loaded and executed
Async <script async>
When parser reaches script tag, it start loading t and executes it when it is loaded.The page loading is continued. This technique however does not provide you exact time when script is going to be loaded and executed.
Something like not synced multi-threading, if you are familiar with threading term. This approach is not so good, because, if you have scripts which depend on each other (for example JQuery and your script which uses it) you will get script errors as your script might load and execute before script on which it depends on. The order of script tag in document is relevant.
Defer <script defer>
Is my favorite and most suitable for most of the cases. It means that parser will start loading script file similar like with async, but it will not execute it until page is loaded.
To make it more clear, the following is diagram of these three methods, so you can easily see the difference.
Adding defer attribute to script tags in my website pages helped me speed up teh website and according to Google PageSpeed Insights my website gained additional 6 speed point :)
Disclaimer
Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.
Comments for this article