DEV Community

Cover image for Defer JavaScript for Faster Load Time
Jack Huynh
Jack Huynh

Posted on • Edited on

Defer JavaScript for Faster Load Time

When it comes to JavaScript speed optimization, there is one technique every developers should know and embrace: Defer JavaScript.

Table Of Contents

  1. The behavior of a website
  2. Why bother defer JavaScript
  3. Async vs Defer
  4. Summary

The behavior of a website

Imaging having an HTML file import 2 scripts: small.js and big.js with difference load times.

<head>
  <script src="big.js"></script> <!-- Load time: 500ms -->

  <script src="small.js"></script> <!-- Load time: 100ms -->
</head>
<body>
  <p>...content...</p>
</body>
Enter fullscreen mode Exit fullscreen mode

During page load, a “white screen” might briefly appear before the full page is visible.

Image description

Why bother defer JavaScript

Due to it's nature, the browser will stop rendering the page while loading and executing scripts.

Image description

As the result, the page content remains hidden until both small.js and big.js are fully downloaded and run.

Image description

The "white-screen" is nearly invisible for users with fast internet connections. However, for those like me with slower speeds, it result in a significant delay before the entire page becomes visible.

Luckily, Defer JavaScript comes to the rescue help us pushing all the script to the bottom of the loading process using defer and async.

Async vs Defer

Async

Async will move the download of your script into the background and execute the script as soon as the download is finished.

Image description

Each async script operates independently, they don't wait for each other. Whatever loads first - run first:

<head>
  <!-- loads first / runs second -->
  <script async src="big.js"></script>

  <!-- loads second / runs first -->
  <script async src="small.js"></script>
</head>
<body>
  <p>...content...</p>
</body>
Enter fullscreen mode Exit fullscreen mode

Defer

Defer will move the download of your script into the background and execute the script as soon as the site finished parsing.

Image description

It will also respect the execution order of your scripts.

<head>
  <!-- loads first / runs first -->
  <script defer src="big.js"></script>

 <!-- loads second / runs second -->
  <script defer src="small.js"></script>
</head>
<body>
  <!-- visible immediately -->
  <p>...content...</p>
</body>
Enter fullscreen mode Exit fullscreen mode

Summary

async and defer both load JavaScript asynchronously without render blocking but with difference in behavior.

Top comments (0)