About
defer 1) is an boolean attribute of script element that indicates to the user agent (browser) that it should execute the script:
- after the DOM has been created (the HTML document read entirely and has been parsed to create the DOM)
- before firing DOMContentLoaded
The scripts with the defer attribute will then prevent the DOMContentLoaded event from firing.
The script will then not block the parsing and rendering of the HTML document. Its download and execution will happen asynchronously
It's one of the resource fetch instructions.
Demo
This demo shows you the event in order that occurs related to the code.
- The script that will be loaded with the defer attribute with the domcontentloaded
// simulate code at the DOM content loaded event
document.addEventListener("DOMContentLoaded", function(event) {
console.log("[5]: 'DOMContentLoaded' event fired");
});
window.addEventListener('load', function(event) {
console.log("[6]: 'load' event fired");
});;
// Simulate a wait of 5 seconds
console.log("[3]: 'defer' script is executing (after the event listener)");
let now = new Date().getTime();
let end = now;
while(end < now + 5000) {
end = new Date().getTime();
}
console.log("[4]: 'defer' script execution ended");
- The HTML page that:
- loads the script (described above)
- execute inline javascript (this code will be called first)
<script>console.log('[1]: DOM is build')</script>
<script defer src="/_export/code/web/html/defer?codeblock=0"></script>
<script>console.log('[2]: DOM was parsed')</script>
- Output:
Async vs Defer
See also the What is the difference between the Async and Defer Script attribute ?