DEV Community

Cover image for Loading JS scripts [A]synchronously
Lourenço Costa
Lourenço Costa

Posted on • Updated on

Loading JS scripts [A]synchronously

load-stript-3
The image above shows the regular flow when we place a <script> in a HTML document. The whole process happens synchronously. The steps are:

  1. HTML parsing starts
  2. HTML parsing pauses when a <script> is found
  3. <script> is loaded
  4. <script> is executed
  5. Finally the HTML parsing is resumed

For this reason, a common practice is to place all the <script> at the bottom of the page, after all the HTML elements are parsed. This is fine, it makes total sense (as long as you are dealing with small files). But let's say you will load a large JS file to a page, such as a library, e.g. In this scenario, although all the HTML is ready, the JavaScript-related functionality will only be available when the JS file is downloaded and executed.
The good news is that there are some surprisingly easy-to-implement alternatives to this approach.

Loading JS scripts asynchronously

async attribute

load-stript-2

By placing the async attribute in a <script> tag, the script will be downloaded without pausing the HTML, but as soon as it finishes downloading, it runs (blocking the HTML parsing while doing so). This approach is very suitable for displaying ads in your page, e.g.

defer attribute

load-stript-1

This is how you get an actual asynchronous JS loading. The defer attribute uses a more "polite" approach towards the HTML document, as it downloads the script, but waits until the HTML parsing is done before running it.

When a pack of wolves is traveling, the older members lead the way, as they move more slowly, which causes the rest of the pack to move at their pace.

What does this have to do with JS loading?

The bigger advantage to using defer is that once the HTML is parsed, the JS scripts will potentially be in a queue, ready to be executed, in the same order as they were inserted in the document. You might want to place the bigger files above the smaller ones (as they take longer to download). Also, by doing so, feel free to place your <scripts> is the <header> of the document, so their download will begin as early as possible!

Loading JS scripts dynamically

Another interesting option is loading a script conditionally, let's say by a click of a button. You can add an eventListener to the button, and use something like the following:



let script = document.createElement('script');
script.src = "my-script.js";
document.body.append(script);

Enter fullscreen mode Exit fullscreen mode




Thanks for the time reading this!

Follow me:
LinkedIn | Dev.to | Buy me a coffee | GitHub

Top comments (0)