HTML <script> defer Attribute
Definition and Usage
defer
attribute is a boolean attribute.
If the defer
attribute specifies that the script should be downloaded in parallel while parsing the page and executed after the page parsing is completed.
Note:defer
attribute is only applicable to external scripts (only if it exists src attribute should be used only when necessary).
Note:External scripts can be executed in multiple ways:
- If async is set: the script is downloaded in parallel while parsing the page and executed immediately when available (before parsing is completed)
- If defer is set (but not async): the script is downloaded in parallel while parsing the page and executed after the page parsing is completed
- If neither async nor defer is specified: the script is downloaded and executed immediately, blocking the page parsing until the script execution is complete
Example
The script will be downloaded in parallel with the page parsing, and executed after the page parsing is complete:
<script src="demo_defer.js" defer></script>
Syntax
<script defer>
Deferring Script Execution
You can control the execution of scripts using the async and defer attributes. The defer attribute tells the browser to execute the script only after the page has been loaded and parsed.
Browsers will defer the loading and execution of scripts until after all elements in the HTML document have been parsed when encountering script elements with the defer attribute.
This is the same result as moving the script to the end of the page:
<body> ... ... ... ... ... ... <script src="demo.js"></script> </body>
Browser Support
The numbers in the table indicate the first browser version to fully support this attribute.
Chrome | Edge | Firefox | Safari | Opera |
---|---|---|---|---|
Chrome | Edge | Firefox | Safari | Opera |
8.0 | 10.0 | 3.5 | 5.0 | 15.0 |