
JavaScript defer
The defer
attribute in JavaScript is used to indicate that the script should be executed after the HTML document has been completely parsed and loaded. When a <script>
tag has the defer
attribute, the browser will continue parsing the HTML content and simultaneously load the script file in the background. The script will then be executed after the parsing is finished.
Here’s an example of using the defer
attribute:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Defer Example</title>
<script src="script.js" defer></script>
</head>
<body>
<h1>Hello, world!</h1>
</body>
</html>
In this example, the script.js
file is loaded with the defer
attribute. The browser will download the script file in the background while parsing the HTML content. Once the parsing is complete, the script will be executed in the order it appears in the document.
Using the defer
attribute is beneficial because it allows scripts to be placed in the <head>
section of the document without blocking the rendering of the HTML content. It also ensures that the scripts are executed in the correct order, even if they are loaded asynchronously.
Note that the defer
attribute is only applicable to external script files and not inline scripts. Also, keep in mind that Internet Explorer does not support defer
for scripts loaded from a data:
URL.