DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 963,673 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for Use of defer and async to limit the effects of blocking scripts in JavaScript
Shruti Kapoor
Shruti Kapoor

Posted on

Use of defer and async to limit the effects of blocking scripts in JavaScript

When a script is loaded, it loads in blocking or synchronous mode, which means that the browser waits for the script to finish loading before executing any code after it.
So in this case, script2.js cannot start loading before script1.js finishes loading -

<body>

<script src="script1.js"> </script>
<script src="script2.js"> </script>

</body>

Enter fullscreen mode Exit fullscreen mode

As you can imagine, this becomes problematic when -

  1. script2 needs variables that are in script1
  2. script1 is really huge, and the entire page needs to wait for the script to finish loading.

The browser waits for the script to finish because it assumes that the script may have code that may update the page contents using document.write. If your script isn't using document.write, then waiting for the browser to finish loading isn't useful.

In order to get past this, there are two attributes that can be used - defer and async.

  1. defer: defer tells browser that script wont generate any document content and can safely be downloaded without blocking the page and this script should be deferred until all the page is downloaded. defer is executed only when the page is completely parsed.
  2. async: async is similar to defer in the sense that it won't change anything in the DOM, but unlike defer, async scripts are executed as soon as they are downloaded. This is advantageous because scripts can potentially execute sooner.

Syntax -

<script defer src="script1.js"> </script>
<script async src="script2.js"> </script>
Enter fullscreen mode Exit fullscreen mode

TL;DR
Blocking scripts can slow down page. Use defer or async to limit effects of blocking script. defer and async scripts must not modify page content using document.write.

  1. defer: defer is executed only when the page is completely parsed.
  2. async: async scripts are executed as soon as they are downloaded

Shruti Kapoor
View all recent blogs
Follow on twitter

Top comments (3)

Collapse
 
ben profile image
Ben Halpern

DEV makes use of these techniques to great success.

Collapse
 
shrutikapoor08 profile image
Shruti Kapoor Author

πŸŽ‰πŸ’―

🌚 Friends don't let friends browse without dark mode.

Good news! You can update to dark mode in your DEV settings.