Definition
The defer attribute is a boolean that determines whether a script should be fetched only after the HTML has been parsed.
Applicable Elements
The defer attribute can be used with the following elements:
HTML <script> defer Attribute
The <script> tag is used to embed a client-side script, such as JavaScript. It can either be embedded directly or through an external file using the src attribute.
The defer attribute, when used with the <script> element, determines whether the script should be fetched only after the HTML has been parsed.
Syntax
<script defer src="https://cdn.ampproject.org/v0.js"></script>Usage
- The
deferattribute is a boolean that determines whether the script should be fetched only after the HTML has been parsed. - The
<script>srcattribute must be present. Thedeferattribute only applies to external scripts. - Scripts with the
deferattribute will be executed in the exact order they appear in the document. - The
deferattribute prevents scripts from blocking the document’s rendering until they are executed and evaluated. This improves the performance of the web page. - The
deferattribute has no effect on module scripts.
There are several ways you can execute an external script:
- If
asynconly, then they are fetched asynchronously. See theasyncattribute. - If
asyncis not present, butdeferis present, then the script is executed after the page has finished parsing. - If neither
asyncnordeferis present, then the script is fetched and executed immediately before the browser continues parsing the rest of the page.
Values
Values can include:
defer
Examples
An example showing a script being deferred until after parsing of the HTML:
<script defer src="https://cdn.ampproject.org/v0.js"></script>Specification
The defer HTML specification for the <script> element is as follows:
Browser Support
The defer attribute has the following browser support:
Desktop
| Chrome | Edge | Firefox | IE | Opera | Safari | |
|---|---|---|---|---|---|---|
defer | Yes | Yes | Yes | Yes | Yes | Yes |
Mobile
| Android Webview | Chrome Android | Firefox Android | Opera Android | iOS Safari | Samsung Internet | |
|---|---|---|---|---|---|---|
defer | Yes | Yes | Yes | Yes | Yes | Yes |
