When a webpage loads a JavaScript file (inside a typical <script> tag), it must download the script, parse it and execute it wherever it sits within the HTML before continuing to render the rest of the HTML page. So the more <script> tags, the longer a page will take to load. The higher up a page that the scripts are included means a smaller amount of the page UI will be loaded before the script is downloaded and executed. This is especially true for third party JavaScript files, as you have less control over the speed of the server that is hosting those files.

There are several ways to handle and mitigate this potential problem.


Asynchronous loading

One of the easiest solutions to implement is async loading of the javascript files. Asynchronous means that data is submitted in parts instead of in one, large dump. This is advantageous in this circumstance as it means that the entire JavaScript file does not need to be downloaded in one go which leads to parser blocking (JS blocking the rest of the UI). This means that the UI thread will load the JavaScript files with the async tag only when it is not loading other page UI elements.


<script async src="https://url.com/jsfile.js"></script>


By simply adding the ‘async’ tag, the browser UI thread understands that it does not need to download the JavaScript in one go, and should not prioritise doing so over loading other page elements.

 – Be careful!

Be very careful when implementing this solution, as with multiple scripts loaded asynchronously, the order that they are loaded onto the page will essentially be randomised. A typical example will be a script that requires jQuery being loaded before jQuery is loaded, causing an error being thrown. The best practice solution here is to bundle scripts appropriately so that those that have requirements will not be loaded separately from the required scripts.


Moving scripts to the footer

The other, much simpler solution is to move the scripts to the bottom of the page. This is so simple as we know that the higher a script on a page, the less of the pages UI that is built and shown before the script is downloaded and run. Therefore if the script is at the bottom of the page, all of the page elements that are above it are loaded in before it is. This guarantees that the scripts won’t block substantial amounts of UI rendering. This is a quick and simple solution, but it will not improve your page speed score (especially on mobile) to the degree that a properly implemented bundled asynchronous script setup will do.