Optimizing JavaScript Loading for Performance : Async vs. Defer

Understanding the differences between async and defer is crucial for optimizing script loading in JavaScript. By utilizing these attributes appropriately, developers can improve page rendering and script execution, leading to better overall performance and user experience.

Optimizing JavaScript Loading for Performance : Async vs. Defer

Understanding the differences between async and defer is crucial for optimizing script loading in JavaScript. By utilizing these attributes appropriately, developers can improve page rendering and script execution, leading to better overall performance and user experience.

Optimizing JavaScript Loading for Performance : Async vs. Defer

Default Behaviour

We generally connect our HTML page with external javascript with <script> tag. Traditionally, JavaScript <script> tags were often placed in the <head> section of the HTML document. However, doing so means that the parsing of the HTML is blocked until the JavaScript file is fetched and executed, leading to slower page load times. Nowadays, we mostly prefer to keep the <script> tag after all the contents of the <body> element to the page get loaded first. <script src="example.js"></script> Here's how HTML parsing and script execution takes place

image

Understanding async and defer:

async:

When the async attribute is included in a script tag, the browser will download the script file asynchronously while simultaneously parsing the HTML document. Once the script file finishes downloading, it will pause HTML parsing, execute the script, and resume parsing. Multiple async scripts can load concurrently, and their execution order may vary.

image

defer:

The defer attribute also allows the browser to download the script file asynchronously. However, unlike async, the script's execution is deferred until the HTML parsing is complete. Multiple defer scripts maintain their order of execution as they appear in the HTML document.

image

Impacts on Page Rendering and Script Execution:

  • async Impact: Using async scripts can speed up the page rendering process since the browser doesn't wait for the script to download and execute before moving forward. However, this can lead to potential issues if scripts depend on each other or manipulate the DOM before it's fully parsed.

  • defer Impact: By utilizing defer, scripts are executed after the HTML parsing is complete. This ensures that scripts don't interfere with the rendering process. It's particularly useful when dependencies exist between scripts or when scripts need to manipulate the DOM. Here’s an example code snippet that demonstrates the behavior of async and defer attributes:

<!DOCTYPE html>
<html>
<head>
  <title>Async and Defer Example</title>
  <script async src="script1.js"></script>
  <script defer src="script2.js"></script>
</head>
<body>
  <h1>Async and Defer Example</h1>
  <p>This is a paragraph.</p>
  <script>
    console.log("Inline script");
  </script>
</body>
</html>

Explanation:

In the code snippet, we have an HTML document that includes two script tags with async and defer attributes, respectively. We also have an inline script and some HTML content.

  • <script async src="script1.js"></script>: This script tag has the async attribute, indicating that the browser should download and execute the script asynchronously. The script file specified by the src attribute will not block the HTML parsing. Once the script finishes downloading, it will pause HTML parsing, execute the script, and resume parsing.

  • <script defer src="script2.js"></script>: This script tag has the defer attribute, indicating that the script file should be downloaded asynchronously. However, unlike async, the execution of the script is deferred until the HTML parsing is complete. The script2.js file will maintain its order of execution as it appears in the HTML document.

  • <script>console.log("Inline script");</script>: This is an inline script that doesn't have any attributes. It will be executed synchronously as part of the HTML parsing process.

The expected behavior when loading the page:

  • The HTML parsing begins, and the <h1> and <p> elements are rendered.

  • The browser encounters the script tag with async (script1.js). It initiates the asynchronous download of the script file while continuing with HTML parsing. The script will execute once it finishes downloading, even if the HTML parsing is not complete. The execution order may vary depending on the network speed.

  • The browser encounters the script tag with defer (script2.js). It also initiates the asynchronous download of the script file but defers its execution until after the HTML parsing is complete. The script2.js file will maintain its order of execution as it appears in the HTML document.

  • The inline script is encountered and executed synchronously as part of the HTML parsing process.

By using async and defer attributes appropriately, we optimize the loading and execution of scripts, allowing the HTML rendering to proceed without significant delays. This helps improve page loading performance and ensures scripts are executed in the desired order based on their dependencies.

Best Practices for Using async and defer:

  • Prioritize Critical Scripts: Place essential scripts, such as those required for rendering or core functionality, directly in the HTML without using async or defer attributes. This ensures that critical scripts are loaded and executed synchronously, avoiding any delays.

  • Use async for Non-Critical Scripts: For scripts that are not essential to the initial page rendering, but can be loaded and executed independently, utilize the async attribute. This allows the browser to download and execute the scripts asynchronously, reducing potential blocking of HTML parsing. Utilize defer for Dependent Scripts: When scripts have dependencies on other scripts or need access to the fully parsed DOM, use the defer attribute. This ensures that dependent scripts are executed in the order specified and have access to the necessary resources.

  • Minimize Script Size: Optimize and minify your scripts to reduce their file size. Smaller scripts download faster, improving overall page loading time. Tools like UglifyJS or Terser can help with script minification.

  • Place Scripts Before Closing Body Tag: To prevent rendering delays and ensure proper DOM access, place script tags just before the closing </body> tag. This allows the browser to render the HTML content before fetching and executing the scripts.

Summary:

Understanding the differences between async and defer is crucial for optimizing script loading in JavaScript. By utilizing these attributes appropriately, developers can improve page rendering and script execution, leading to better overall performance and user experience. Remember to prioritize critical scripts, use async for non-blocking scripts, leverage defer for dependencies, minimize script size, and position scripts wisely within the HTML structure. Following these best practices will help ensure efficient script loading and enhance the performance of your web pages.

Ref : Async vs. Defer: Optimizing JavaScript Loading for Performance

Async vs Defer in JavaScript: Which is Better?

aung thu oo

#HIRE ME

HIRE ME!

Aung Thu Oo

Having over 15 years of working experience in Laravel, PHP, Flutter, Node.Js, Vue.JS, JAVA. Strong information technology professional with a degree i...

View detail