javascript
  1. javascript-defer

JavaScript Defer

Syntax

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

Example

<!DOCTYPE html>
<html>
<head>
    <title>JavaScript Defer Example</title>
    <script defer src="script.js"></script>
</head>
<body>
    <h1>Hello, World!</h1>
</body>
</html>

Output

The script will be downloaded in the background while the browser continues to parse the HTML document and render the page. When the parsing is finished, the script will be executed.

Explanation

The defer attribute is used to tell the browser to download the script in parallel to parsing the HTML document, but not execute it until the document parsing is finished. This can lead to faster page load times and better user experience, as the user can see the page content while the script is being downloaded.

Use

Use defer when the script does not need to be executed immediately, and when it does not manipulate the HTML content of the page (since the HTML parsing is finished before the script is executed).

Important Points

  • The defer attribute only works for external script files, not inline scripts.
  • Multiple scripts with defer will be downloaded and executed in the order they appear in the document.
  • The defer attribute is not supported in older browsers, such as Internet Explorer 9 and below.

Summary

JavaScript defer attribute tells the browser to download a script in parallel to parsing the HTML document, but not execute it until the document parsing is finished. It can lead to faster page load times and better user experience. However, it should only be used for scripts that do not need to be executed immediately and do not manipulate the HTML content of the page.

Published on: