How to Execute a Script Asynchronously in HTML5 ?


Script tag is used to make the webpage dynamic, however heavy scripts can result in slow rendering of the webpage which ultimately results in poor user experience. To solve this issue, we asynchronously execute the scripts in the webpage i.e. the javascript is downloaded in parallel with other website elements and starts to execute as soon as it is completed.

To load scripts asynchronously two popular approaches used are:

  • Async attribute: The scripts are downloaded in parallel and start to execute as soon as downloading is complete.

  • Defer attribute: The scripts are downloaded in parallel and only starts to execute after the page parsing process is finished.

In absence of any of these attributes, the script starts to execute immediately after it is downloaded, also resulting in blocking the parsing process.

Approach 1: Async Attribute

In this example, we will examine to asynchronously execute scripts using the async tag available in JavaScript.

Syntax

<script src="..." async></script>

async is a boolean attribute which is true when defined within <>, else it is set to false by default.

Algorithm

Step 1 :Define webpage skeleton with HTML tags

Step 2 :Import scripts using <script > tag

Step 3 :Add async attribute in <script> tag

Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Async Javascript</title>
</head>
<body>
    <h1>Tutorials Point</h1>
    <script type="text/javascript"
    src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js" async></script>

    <!-- Loaded after sometime if aysnc attribute is removed -->
    <h3>Welcome to Tutorials point</h3>
    <p>
        Lorem ipsum dolor sit amet consectetur, adipisicing elit. Nulla debitis deleniti harum perferendis quisquam,
        cum dignissimos ex laborum saepe pariatur sapiente dolores possimus autem quam voluptates commodi a eveniet facere!
    </p>
    <button onclick="window.location.reload()">Reload</button>
</body>
</html>

There are a few important things to remember while utilising async:

  • Regardless of where they are located within the HTML file, scripts with the async property start running as soon as they are downloaded. This implies that a script may result in problems or unexpected behaviour if it depends on other resources, such pictures or stylesheets, that haven't yet finished loading.

  • The sequence in which scripts with the async property run in the HTML file is not known in prior. If the sequence of execution matters, when one script depends on the other, this might be troublesome.

  • Scripts with the async attribute do not block the rendering of the page. Though the page’s load time is improved, this can also lead to an instance where the contents are unstyled or other visual glitches.

In order to eliminate these problems, HTML5 provides a defer attribute that allows scripts to download asynchronously and ensures that scripts that rely on other resources are executed in the correct order and reduces the possibility of errors or glitches.

Approach 2: Defer attribute

In this example we will show how to load script using defer attribute set to true.

Syntax

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

defer is a boolean attribute which is true when defined within <>, else it is set to false by default.

Algorithm

Step 1 :Define webpage skeleton with HTML tags

Step 2 :Import scripts using <script > tag

Step 3 :Add defer attribute in <script> tag

Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Async Javascript</title>
</head>
<body>
    <h1>Tutorials Point</h1>
    <script type="text/javascript"
    src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js" defer></script>

    <!-- Loaded after sometime if defer attribute is removed -->
    <h3>Welcome to Tutorials Point</h3>
    <p>
        Lorem ipsum dolor sit amet consectetur, adipisicing elit. Nulla debitis deleniti harum perferendis quisquam,
        cum dignissimos ex laborum saepe pariatur sapiente dolores possimus autem quam voluptates commodi a eveniet facere!
    </p>
    <button onclick="window.location.reload()">Reload</button>
</body>
</html>

From the output we can see that the <h1> header content loads immediately after loading the webpage but <h3> and <p> content took a while to load after that, which is blocked due to execution of scripts. However, no such issues are encountered when async and defer attribute is used with script tag.

Conclusion

The async/defer attribute in HTML5 enables asynchronous loading of scripts. When a script with the async property is encountered, the browser downloads the script at the background when the page is still rendering.

The async/defer attribute in HTML5 enables asynchronous loading of scripts. When a script with the async property is encountered, the browser downloads the script at the background when the page is still rendering.

Updated on: 09-Aug-2023

185 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements