In JavaScript, the defer attribute is used in the
When a script is deferred, it will not block the parsing of the HTML document. Instead, it will be executed in the order it appears in the HTML after the HTML parsing is complete.
Here's an example of using the defer attribute:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Defer Example</title> <!-- Include a deferred script --> <script defer src="script.js"></script> </head> <body> <div> <article>This is some content in the body of the HTML document.</article> </div> </body> </html>
The `script.js` file will be executed after the HTML document has been completely parsed.
The defer attribute ensures that the script will be executed in order and after the HTML parsing is finished.
It's important to note that multiple scripts with the defer attribute will be executed in the order they appear in the HTML document.
This allows us to control the order of script execution without blocking the HTML parsing.
Here's an example with multiple deferred scripts:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Multiple Deferred Scripts</title> <!-- Include multiple deferred scripts --> <script defer src="script1.js"></script> <script defer src="script2.js"></script> </head> <body> <div> <article>This is some content in the body of the HTML document.</article> </div> </body> </html>
Using the "defer" attribute is particularly useful when we want to ensure that our scripts don't block the rendering of the HTML page, making the page "load faster", especially for "larger scripts" or scripts that are not "critical" for the initial rendering of the page.