HTML script defer Property: Deferred Script Loading Explained

The defer attribute in the HTML <script> tag is a boolean attribute that instructs the browser to download the script in the background while parsing the HTML. The script will only execute after the HTML parsing is complete. Using defer can significantly improve page load performance, especially when the script is not essential for the initial rendering of the page. This article explores the defer attribute in detail, providing practical examples and best practices.

What is the defer Attribute?

The defer attribute is a boolean attribute used with the <script> tag. When defer is present, the browser downloads the script asynchronously without blocking the HTML parsing. The key difference from async is that scripts with defer are guaranteed to execute in the order they appear in the HTML document, and only after the HTML parsing is complete.

Purpose of the defer Attribute

The primary purposes of the defer attribute are:

  • Non-Blocking Download: Allows the browser to continue parsing the HTML while the script is being downloaded in the background.
  • Ordered Execution: Ensures that scripts are executed in the order they appear in the HTML.
  • Execution After HTML Parsing: Guarantees that the script is executed only after the entire HTML document has been parsed.
  • Improved Performance: Enhances the perceived loading speed of the webpage by not blocking the rendering process.

Syntax of the defer Attribute

The defer attribute is a boolean attribute, so its presence indicates that it is enabled.

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

Here, the defer attribute is applied to the <script> tag, instructing the browser to defer the execution of script.js until after the HTML document has been parsed.

defer Attribute Details

Here’s a detailed table explaining the attributes:

Attribute Value Description
`defer` `defer` A boolean attribute. If present, it indicates that the script is executed after the page has finished parsing.

Examples of Using the defer Attribute

Let’s explore practical examples of how to use the defer attribute to improve the loading performance of your web pages.

Basic Example: Deferring a Simple Script

This example demonstrates deferring a simple script that manipulates the DOM.

<!DOCTYPE html>
<html>
  <head>
    <title>Defer Example</title>
  </head>
  <body>
    <p id="defer-demo">Original text.</p>
    <script src="defer-script1.js" defer></script>
  </body>
</html>
// defer-script1.js
document.getElementById("defer-demo").textContent =
  "Text updated by deferred script!";

In this case, the script defer-script1.js will be downloaded in the background and executed after the HTML has been parsed, ensuring that the DOM element with id="defer-demo" exists before the script attempts to modify it.

Multiple Deferred Scripts

This example shows how multiple deferred scripts are executed in the order they appear in the HTML.

<!DOCTYPE html>
<html>
  <head>
    <title>Multiple Defer Example</title>
  </head>
  <body>
    <p id="defer-demo2">First script: Original text.</p>
    <script src="defer-script2.js" defer></script>
    <p id="defer-demo3">Second script: Original text.</p>
    <script src="defer-script3.js" defer></script>
  </body>
</html>
// defer-script2.js
document.getElementById("defer-demo2").textContent =
  "First script: Text updated by first deferred script!";
// defer-script3.js
document.getElementById("defer-demo3").textContent =
  "Second script: Text updated by second deferred script!";

The scripts defer-script2.js and defer-script3.js will be executed in the order they appear in the HTML, ensuring that the first script updates the first paragraph and the second script updates the second paragraph.

Using defer with External Libraries

This example demonstrates using defer with external libraries like jQuery.

<!DOCTYPE html>
<html>
  <head>
    <title>Defer with Library Example</title>
  </head>
  <body>
    <p id="defer-demo4">Library: Original text.</p>
    <script
      src="https://code.jquery.com/jquery-3.6.0.min.js"
      defer
    ></script>
    <script src="defer-script4.js" defer></script>
  </body>
</html>
// defer-script4.js
$(document).ready(function () {
  $("#defer-demo4").text("Library: Text updated by deferred script!");
});

The jQuery library and defer-script4.js will be downloaded asynchronously, and defer-script4.js will execute after jQuery is loaded and the DOM is ready, updating the text content of the paragraph.

Dynamic Script Loading with defer

While defer is primarily used with <script> tags directly in the HTML, you can dynamically create and append a <script> tag with the defer attribute using JavaScript.

<!DOCTYPE html>
<html>
  <head>
    <title>Dynamic Defer Example</title>
  </head>
  <body>
    <p id="defer-demo5">Dynamic: Original text.</p>
    <script>
      function loadDeferredScript(url) {
        var script = document.createElement("script");
        script.src = url;
        script.defer = true;
        document.head.appendChild(script);
      }
      loadDeferredScript("defer-script5.js");
    </script>
  </body>
</html>
// defer-script5.js
document.getElementById("defer-demo5").textContent =
  "Dynamic: Text updated by deferred script!";

In this case, the script defer-script5.js is dynamically created and appended to the <head> with the defer attribute set to true. The script will be downloaded and executed after the HTML parsing is complete.

Best Practices for Using defer

To effectively use the defer attribute, consider the following best practices:

  • Use defer for non-essential scripts: Apply defer to scripts that are not critical for the initial rendering of the page, such as analytics, social media widgets, or non-essential UI enhancements.
  • Ensure script order is maintained: If your scripts have dependencies, ensure that they are included in the correct order in the HTML to guarantee proper execution.
  • Test across different browsers: While defer is widely supported, test your implementation across different browsers to ensure consistent behavior.
  • Combine with minification and bundling: To further optimize loading performance, combine defer with minification and bundling techniques to reduce the size and number of script files.
  • Avoid document.write(): Scripts loaded with defer should not use document.write(), as it can lead to unexpected behavior and negatively impact performance.

When to Use defer vs. async

  • defer:
  • Use when the order of script execution matters.
  • Use when the script depends on the DOM being fully parsed.
  • Suitable for scripts that enhance the page but are not critical for initial rendering.
  • async:
  • Use when the order of script execution does not matter.
  • Use when the script is independent and does not rely on other scripts or the DOM.
  • Suitable for scripts like analytics or ad loaders that can be executed as soon as they are downloaded.

Browser Support

The defer attribute is widely supported across modern browsers. Here’s a summary of browser compatibility:

  • Chrome: Supported
  • Edge: Supported
  • Firefox: Supported
  • Safari: Supported
  • Opera: Supported
  • Internet Explorer: Supported (IE 10+)

Note: Always test your implementation across different browsers to ensure a consistent user experience. 🧐

Conclusion

The defer attribute is a valuable tool for improving the loading performance of your web pages by allowing scripts to be downloaded asynchronously and executed after the HTML has been parsed. By understanding how to use defer effectively, you can create faster, more responsive web experiences for your users. Remember to follow the best practices outlined in this guide to ensure optimal results. Happy coding!