Boosting Web Page Performance with the Defer Attribute

JavaScript plays a vital role in enhancing the interactivity and functionality of web pages. However, the way scripts are loaded can significantly impact the user experience and overall performance of a website. In this article, we'll delve into the defer attribute in JavaScript, exploring its purpose, benefits, and practical examples, including implementations in ES8 and TypeScript.

Defer Attribute Overview

The defer attribute is a Boolean value used to signal that a script should be executed after the HTML document has been fully parsed. This attribute exclusively works with external scripts, meaning scripts specified with the src attribute within the <script> tag. When the defer attribute is present, it indicates that the script won't generate any content, allowing the browser to continue parsing the rest of the page without interruption. Importantly, a script with the defer attribute does not block the page, contributing to a smoother user experience.

Let's visualize the impact of the defer attribute with the help of an example:

This attribute informs the browser to execute the specified script file only when the entire HTML document has been parsed. By using defer, we optimize performance and memory usage, preventing potential delays in content rendering.

Syntax of Defer Attribute

<script defer></script>

Example 1. Basic Implementation of Defer Attribute

Consider the following example, where an external JavaScript file (myscript.js) is included with the defer attribute.

<!DOCTYPE html>  
<html lang="en">  
<head>  
  <script src="myscript.js" defer></script>  
</head>  
<body>  
  <div>  
    <h1>javaTpoint.com</h1>  
    <h3>This is an example of the defer attribute.</h3>  
  </div>  
</body>  
</html>
//myscript.js

alert("Hello World. \nWelcome to the javaTpoint.com \nThis is an example of the defer attribute.");

In this example, the external script myscript.js is deferred, ensuring it executes after the HTML document is fully parsed. The alert will be triggered once the document parsing is complete.

Example 2. Improving Loading Performance with Defer

In scenarios where scripts may have extended loading times, using the defer attribute becomes crucial. This can prevent situations where the script's loading time leads to a blank page instead of displaying content. This is especially beneficial for mobile devices with limited memory resources.

Example 3. Handling Defer Attribute in Older Browsers

While defer is a powerful feature, it may not be supported in older browsers. In such cases, an alternative solution involves placing the script section just before the closing </body> tag in the HTML file. This ensures that script execution occurs after the HTML content has been loaded.

<body>  
  <!-- Other HTML content -->

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

Example 4. Leveraging Defer in TypeScript (ES8)

Now, let's explore how to implement the defer attribute using TypeScript in an ES8 environment. TypeScript adds a layer of type safety to our JavaScript code, making it more robust.

let message: string = "Hello from TypeScript!";
console.log(message);

Compile the TypeScript file using the TypeScript compiler (tsc).

tsc script.ts

Include the generated JavaScript file in the HTML.

<!DOCTYPE html>  
<html lang="en">  
<head>  
  <script src="script.js" defer></script>  
</head>  
<body>  
  <div>  
    <h1>javaTpoint.com</h1>  
    <h3>This is an example of TypeScript with the defer attribute.</h3>  
  </div>  
</body>  
</html>

In this example, we demonstrate the seamless integration of TypeScript with the defer attribute, combining the benefits of type safety with optimized script loading.

Throughout this exploration, we uncovered the fundamental role of the defer attribute, emphasizing its capacity to orchestrate script execution after the HTML document has been fully parsed. By seamlessly integrating with external scripts, defer allows browsers to continue parsing the page without interruptions, a crucial factor in delivering a seamless user experience. Our journey through practical examples showcased the versatility of defer, from its fundamental implementation to scenarios where it becomes a performance savior. We witnessed how to defer contributes to improving loading performance, especially in situations where scripts might otherwise cause delays or hinder content display, particularly on resource-constrained mobile devices. As with any technological innovation, it's essential to be mindful of compatibility issues. While defer may not be supported in older browsers, our exploration provided an alternative solution—placing script sections just before the closing </body> tag—an approach that ensures graceful degradation in such scenarios.

Furthermore, we ventured into the realm of TypeScript in an ES8 environment, demonstrating that the advantages of type safety can seamlessly coexist with the optimized loading capabilities of defer. This harmonious integration underlines the adaptability and forward-looking nature of this scripting language. In essence, mastering the defer attribute is not just about syntax and implementation; it's about architecting web pages that deliver unparalleled performance and user satisfaction. As you continue your journey in web development, consider the defer attribute not just as a tool but as a strategic ally in the pursuit of crafting highly responsive and efficient applications. Harness the power of defer, fine-tune your script loading strategies, and embark on a path where every millisecond counts in delivering an exceptional user experience. With defer as your ally, the stage is set for a web development journey where performance is not just a feature—it's a hallmark of excellence.

In the attachment source code, the file structure is as follows.

  1. index.html includes an external script (deferredScript.js) with the defer attribute.
  2. deferredScript.js contains a simple alert statement to showcase the execution behavior.
  3. deferredScript.ts is a TypeScript file for demonstrating TypeScript compatibility.
  4. alternative-script.html demonstrates an alternative script placement strategy just before the closing </body> tag.
  5. Both alternativeScript.js and alternativeScript.ts follow a similar structure to their counterparts.


Similar Articles