Are Dynamically Injected Scripts Loaded Asynchronously by Default?

When you dynamically create a <script> tag and append it to the body of the document, it is executed asynchronously by default. This means that:

  1. The script is fetched and executed in the background without blocking the rendering of the rest of the page;
  2. The script will be executed as soon as it's downloaded, without waiting for other parts of the page to finish loading;
  3. When multiple scripts are loaded asynchronously, the order of execution is not guaranteed and is determined by the script that completes downloading first.

For example, the following script will be fetched and executed asynchronously:

const script = document.createElement('script');
script.src = 'file.js';
document.body.appendChild(script);

If you want to explicitly mark the script to not be asynchronous, you can set the async property of the dynamically created script to false, for example, like so:

const script = document.createElement('script');
script.src = 'file.js';
script.async = false;
document.body.appendChild(script);

In this case, the script will be appended to a list of scripts that will execute in order, as soon as possible.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.