avatarAnkit Tanna

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

3471

Abstract

d and loaded. It’s a good choice for scripts that might rely on the structure of the HTML document or interact with DOM elements. <code>defer</code> ensures that the script doesn’t run until the page is ready, making it suitable for many common use cases.</p><p id="5105">Let us take a look at a snippet of code and try to understand which script loads when graphically:</p><div id="ff58"><pre><span class="hljs-tag"><<span class="hljs-name">script</span> <span class="hljs-attr">async</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"async1.js"</span>></span><span class="hljs-tag"></<span class="hljs-name">script</span>></span> <span class="hljs-comment"><!-- loads in 300ms --></span> <span class="hljs-tag"><<span class="hljs-name">script</span> <span class="hljs-attr">defer</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"defer1.js"</span>></span><span class="hljs-tag"></<span class="hljs-name">script</span>></span> <span class="hljs-comment"><!-- loads in 200ms --></span> <span class="hljs-tag"><<span class="hljs-name">script</span> <span class="hljs-attr">defer</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"defer2.js"</span>></span><span class="hljs-tag"></<span class="hljs-name">script</span>></span> <span class="hljs-comment"><!-- loads in 300ms --></span> <span class="hljs-tag"><<span class="hljs-name">script</span> <span class="hljs-attr">async</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"async2.js"</span>></span><span class="hljs-tag"></<span class="hljs-name">script</span>></span> <span class="hljs-comment"><!-- loads in 50ms --></span> <span class="hljs-tag"><<span class="hljs-name">script</span> <span class="hljs-attr">async</span> <span class="hljs-attr">defer</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"asyncdefer.js"</span>></span><span class="hljs-tag"></<span class="hljs-name">script</span>></span> <span class="hljs-comment"><!-- loads in 60ms --></span></pre></div><p id="ffde">In the above html code, we are loading 5 scripts. We have also indicated the time it takes for each of the script to load.</p><p id="422b">The correct order in which the script files get loaded and executed:</p><ol><li>async2.js</li><li>asyncdefer.js</li><li>async1.js</li><li>defer1.js</li><li>defer2.js</li></ol><p id="0f07">Let us understand this in a bit of depth. Let us assume that we have a normal script tag <b>without async or defer</b>.<b> </b>Refer to the below diagram:</p><figure id="91d8"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*4ThbZRX9kYDMvyZaIOuOew.png"><figcaption>A <script> tag with no async or defer attribute</script></figcaption></figure><p id="0d46">The diagram shows that are two threads which run when a page is loaded. One is the <b>main </b>thread and another is <b>network </b>thread. The main thread starts with the <b>parsing</b> of the HTML. As soon as it encounters a script tag, it then switches to network thread and <b>downloads</b> the script from the internet. It then <b>executes</b> the downloaded script and then continues parsing the rest of the HTML. So, these kind of scripts are basically known as <b>render-blocking </b>scripts. If you have multiple such scripts, the parsing of the HTML would be blocked multiple times. This is not

Options

great if you care to show something to the users really fast.</p><p id="087d">These kind of pauses can be avoided if we have <b>async attribute </b>on the script tags. Let’s see what happens when we encounter a script with an <b>async attribute</b>. Have a look at the diagram below:</p><figure id="1522"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*E8WUFJMMqrTDxd6CoU-JNQ.png"><figcaption>A <script> tag with async attribute</script></figcaption></figure><p id="d3e5">The diagram shows that when it encounters a script with an async attribute, the main thread does not stop parsing the HTML. It downloads the script in <b>parallel</b> and <b>continues</b> parsing the HTML. Once the download is complete, the main thread <b>pauses </b>the parsing of HTML and <b>executes</b> the script which is downloaded. Once the execution is completed, it <b>resumes</b> the parsing of HTML. Scripts get executed as soon as they are downloaded and are <b>not render-blocking.</b></p><p id="4fe9">The <b>defer</b> scripts are also <b>not render-blocking</b> and we still fetch the scripts as soon as they are discovered but they are <b>not executed until the parsing of the HTML is complete</b>. Refer the below diagram to get more understanding of it:</p><figure id="ee6b"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*wS6Yn2_jD74NaOk3yIryHQ.png"><figcaption>A <script> tag with defer attribute</script></figcaption></figure><p id="fd37">The diagram shows that as soon as the script tag with defer attribute is discovered, the download takes place but the parsing of the HTML does not stop. The execution of the downloaded script happens only when the entire HTML is parsed. The defer scripts does guarantee the order of the script execution. So if you had 2 scripts with defer attributes, the script execution would happen only in the sequence of which they were discovered. Scripts with defer attribute are a much better alternative for the scripts that rely on each other but are not render-blocking.</p><figure id="4ca9"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*DqbkmMeMkLbk3Mm5f8TE7w.png"><figcaption>Diagram with all 5 scripts</figcaption></figure><p id="81b6">The async attribute takes precedence over defer attribute. Hence if a script tag has both async and defer, it will be treated as an async script.</p><p id="f529">I hope you enjoyed this article about async and defer scripts. Please share it with your frontend friends.</p><h1 id="456d">PlainEnglish.io 🚀</h1><p id="b16c"><i>Thank you for being a part of the In Plain English community! Before you go:</i></p><ul><li><i>Be sure to <b>clap</b> and <b>follow</b> the writer</i><b></b></li><li><i>Learn how you can also <a href="https://plainenglish.io/blog/how-to-write-for-in-plain-english"><b>write for In Plain English</b></a></i></li><li><i>Follow us: <a href="https://twitter.com/inPlainEngHQ"><b>X</b></a><b> | <a href="https://www.linkedin.com/company/inplainenglish/">LinkedIn</a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw">YouTube</a> | <a href="https://discord.gg/in-plain-english-709094664682340443">Discord</a> | <a href="https://newsletter.plainenglish.io/">Newsletter</a></b></i></li><li><i>Visit our other platforms: <a href="https://stackademic.com/"><b>Stackademic</b></a><b> | <a href="https://cofeed.app/">CoFeed</a> | <a href="https://venturemagazine.net/">Venture</a></b></i></li></ul></article></body>

Web development fundamentals

Master the async and defer Scripts in HTML

What it takes to be a good Web developer? — async and defer execution order

In the world of web development, optimizing the performance of your websites is paramount. When it comes to loading JavaScript resources, the attributes async and defer play a pivotal role in achieving efficient, faster-loading web pages. These attributes offer web developers the means to control how scripts are fetched and executed, ensuring that your web content not only loads swiftly but also functions as intended. In this article, we’ll delve into the nuances of async and defer, shedding light on how they impact the loading and execution of scripts in JavaScript, and when to best utilise each attribute to enhance the overall user experience.

What is async keyword?

In the context of the

Since scripts with async are loaded asynchronously, they may not execute in the order they appear in the HTML document. This means that if you have multiple scripts with async, they could run in an unpredictable order. As a result, async is typically recommended for scripts that don’t depend on the order of execution or other scripts.

These scripts are often suitable for third-party scripts or non-critical scripts that enhance the user experience but don’t need to be executed immediately. It’s essential to be cautious when using async with scripts that rely on specific execution sequences or have dependencies on other scripts.

What is defer keyword?

In the context of the

When a script with the defer attribute is encountered in the HTML, the browser starts downloading it immediately but defers its execution until the HTML parsing is finished. This ensures that the script does not block the rendering of the page, allowing other page elements to load and render first.

Scripts with the defer attribute will execute in the order they appear in the HTML document. This means that if you have multiple defer scripts, they will run sequentially, maintaining the order in which they are declared in the HTML.

defer is typically used for scripts that need to be executed after the document’s DOM (Document Object Model) is fully parsed and loaded. It’s a good choice for scripts that might rely on the structure of the HTML document or interact with DOM elements. defer ensures that the script doesn’t run until the page is ready, making it suitable for many common use cases.

Let us take a look at a snippet of code and try to understand which script loads when graphically:

<script async src="async1.js"></script>            <!-- loads in 300ms -->
<script defer src="defer1.js"></script>            <!-- loads in 200ms -->
<script defer src="defer2.js"></script>            <!-- loads in 300ms -->
<script async src="async2.js"></script>            <!-- loads in 50ms -->
<script async defer src="asyncdefer.js"></script>  <!-- loads in 60ms -->

In the above html code, we are loading 5 scripts. We have also indicated the time it takes for each of the script to load.

The correct order in which the script files get loaded and executed:

  1. async2.js
  2. asyncdefer.js
  3. async1.js
  4. defer1.js
  5. defer2.js

Let us understand this in a bit of depth. Let us assume that we have a normal script tag without async or defer. Refer to the below diagram:

A

The diagram shows that are two threads which run when a page is loaded. One is the main thread and another is network thread. The main thread starts with the parsing of the HTML. As soon as it encounters a script tag, it then switches to network thread and downloads the script from the internet. It then executes the downloaded script and then continues parsing the rest of the HTML. So, these kind of scripts are basically known as render-blocking scripts. If you have multiple such scripts, the parsing of the HTML would be blocked multiple times. This is not great if you care to show something to the users really fast.

These kind of pauses can be avoided if we have async attribute on the script tags. Let’s see what happens when we encounter a script with an async attribute. Have a look at the diagram below:

A

The diagram shows that when it encounters a script with an async attribute, the main thread does not stop parsing the HTML. It downloads the script in parallel and continues parsing the HTML. Once the download is complete, the main thread pauses the parsing of HTML and executes the script which is downloaded. Once the execution is completed, it resumes the parsing of HTML. Scripts get executed as soon as they are downloaded and are not render-blocking.

The defer scripts are also not render-blocking and we still fetch the scripts as soon as they are discovered but they are not executed until the parsing of the HTML is complete. Refer the below diagram to get more understanding of it:

A

The diagram shows that as soon as the script tag with defer attribute is discovered, the download takes place but the parsing of the HTML does not stop. The execution of the downloaded script happens only when the entire HTML is parsed. The defer scripts does guarantee the order of the script execution. So if you had 2 scripts with defer attributes, the script execution would happen only in the sequence of which they were discovered. Scripts with defer attribute are a much better alternative for the scripts that rely on each other but are not render-blocking.

Diagram with all 5 scripts

The async attribute takes precedence over defer attribute. Hence if a script tag has both async and defer, it will be treated as an async script.

I hope you enjoyed this article about async and defer scripts. Please share it with your frontend friends.

PlainEnglish.io 🚀

Thank you for being a part of the In Plain English community! Before you go:

Web Development
JavaScript
HTML
Performance
Web Design
Recommended from ReadMedium