DEV Community

Imamul I. nAyeem
Imamul I. nAyeem

Posted on

Add a script to the HTML header but delay its execution

To add a script to the HTML header but delay its execution until later, you can use the async or defer attribute in the script tag. Both attributes allow the HTML parser to continue parsing the HTML document while the script is being downloaded and then execute the script when it's ready.

Here's an example using the defer attribute:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Your Page Title</title>
    <!-- Add your other head elements here -->

    <!-- Add your script with defer attribute -->
    <script defer src="your-script.js"></script>
</head>
<body>
    <!-- Your page content goes here -->
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

With the defer attribute, the script will be executed in order, after the HTML has been fully parsed. If you have multiple scripts with the defer attribute, they will be executed in the order in which they appear in the HTML.

It's worth noting that the defer attribute only works for external scripts (those with a src attribute pointing to an external file).

Alternatively, you can use the async attribute if the order of script execution is not important:

<!-- Add your script with async attribute -->
<script async src="your-script.js"></script>
Enter fullscreen mode Exit fullscreen mode

Scripts with the async attribute will be executed as soon as they are downloaded, without waiting for the HTML parsing to complete. Keep in mind that using async may not guarantee the order of script execution, so it's suitable for independent scripts.

Top comments (0)