Defer a Script

Description

You can control the execution of a script by using the async and defer attributes.

The defer attribute tells the browser not to execute the script until the page has been loaded and parsed.

To understand the benefit of the defer attribute, let's look at the problem that it solves.

Suppose simple2.js script file has a single statement listed as follows.


document.getElementById("myID").innerText = "myValue";

When this script runs, it will find an element with an id attribute value of myID and change the inner text of that element to myValue.

The following HTML document references the script file using a script element.


<!DOCTYPE HTML>
<html>
<head>
   <script src="simple2.js"></script>
</head>
<body>
   <p id='myID'>This is a test.</p>
</body>
</html>

The default behavior for a browser when it encounters a script element is to stop processing the HTML document, load the script file, and execute its contents.

This means that the browser loads and executes the statement in simple2.js before it has parsed the rest of the HTML, and discovered the p element.

The script doesn't find the element it is looking for, and so no changes are applied.

After the script completes, the browser continues parsing the HTML, and finds the p element.

To solve this problem, put the script element at the end of the document.


<!DOCTYPE HTML>
<html>
<body>
  <p id='myID'>This is a test.</p>
  <a href="http://java2s.com">Visit java2s.com</a>
  <script src="simple2.js"></script>
</body>
</html>

Example

In HTML5 you can achieve the same effect by using the defer attribute. When a browser encounters a script with the defer attribute, it holds off loading and executing the script until all of the elements in the HTML document have been parsed.


<!DOCTYPE HTML>
<html>
<head>
   <script defer src="simple2.js"></script>
</head>
<body>
   <p id='myID'>This is a test.</p>
   <a href="http://java2s.com">java2s.com</a>
</body>
</html>

You can use the defer attribute on external script files only. It doesn't work for inline scripts.





















Home »
  HTML CSS »
    HTML »




HTML Introduction
HTML Document
HTML Section
HTML Group Content
HTML Text Marker
HTML Table
HTML Form
HTML Embed