What’s the difference between async vs defer attributes

Posted: 08 March 2018, Category: Coding

What's the difference between async vs defer attributes

According to https://caniuse.com/ website, async and defer attributes for the <script> element have great support and I think it might be a good time to learn what they do and how to use them.

JavaScript is considered a "parser blocking resource" causing blocking of HTML parsing. Thankfully, the latest technologies such as HTML5 gives you 3 ways to tell browser when to run JavaScript code.

<script>

        
  <script src="myscript.js"></script>
        
      

The HTML is parsed until the <script> tag is reached. At that point, parsing of HTML is blocked and a request is made to fetch the script file. Once the script is executed, HTML parsing resumes again.

<script async>

        
  <script async src="myscript.js"></script>
        
      

With async (asynchronous) attribute, the HTML is parsed while the browser loads and execute the script at the same time. The script execution can happen whenever the script becomes ready (potentially before HTML parsing completes) after being fetched in parallel with the document parsing.

<script defer>

        
  <script defer src="myscript.js"></script>
        
      

With defer attribute in place, the script file is downloaded in parallel while the HTML document is still parsing. However, even if the script file is fully downloaded long before the document is finished HTML parsing, the script is not executed until the HTML parsing is complete.

Note: The async and defer attrib­utes are ignored for scripts that have no src attribute.

Usage:

Use async attribute if the content of page does not rely on any scripts.

Use defer attribute if the content of page rely on script as you want to trigger this script when HTML is fully loaded.

Conclusion

The current trend is to put scripts in the <head> tag and use the async or defer attributes as this allows your scripts to be downloaded asap without blocking your browser.

If you prefer to go with plain <script> tag only, make sure to put it at the bottom before closing </body> tag as this ensures the HTML parser isn't blocked until the very end.

Reference

Back to Blog page

Blog categories

Twitter feed

(17 days ago)
"WTF is this - Understanding the this keyword, call, apply, and bind in JavaScript" by @tylermcginnis https://t.co/z1K7FgeCh4


(19 days ago)
Nice article about JavaScript Scope and Closures. See https://t.co/Is5ICt54bI


(22 days ago)
“Designing for accessibility is not that hard” by @pablostanley https://t.co/qju6oLa5Fs


(about 1 month ago)
Material Design Icons, 2500+ glyph webfont. https://t.co/cF502EgR2Y #MaterialDesign via @MaterialIcons


Top of page