In JavaScript, the defer attribute is used in the <script> tag to indicate that the script should be executed after the HTML document has been fully parsed. When the browser encounters a script with the defer attribute, it will continue parsing the HTML document while simultaneously downloading the script in the background. The script, however, will not be executed until the HTML parsing is complete.
This attribute is useful for ensuring that the script doesn’t block the rendering of the page, leading to faster page loading times. It’s particularly beneficial when the script relies on elements in the HTML document, as it ensures that those elements are available when the script runs.
Here’s an example of how to use the defer attribute:
<script defer src="your-script.js"></script>
By using defer, we allow the HTML to load and render without waiting for the script to be fully downloaded and executed.