defer
defer Attribute
The defer
attribute is a boolean attribute used in <script>
tags. It ensures that a script executes only after the document has been fully parsed. This improves page loading performance by preventing scripts from blocking the rendering process. Scripts with defer
run before the DOMContentLoaded
event but after the HTML is completely loaded.
Syntax
<script defer>
Example
<script id="el" src="/example.js" defer></script>
const el = document.getElementById("el");
console.log(el.defer); // Output: true
Value
- A boolean
defer
attribute in the <script>
tag ensures that script.js
runs only after the HTML document has been fully parsed, enhancing performance.Explanation and Usage
The defer
attribute allows scripts to load while the page is being parsed but delays execution until parsing is complete.
Key Differences Between Script Loading Methods
async
: Loads and runs the script as soon as it is available, potentially interrupting page parsing.defer
(withoutasync
): Loads the script in parallel with page parsing but executes only after parsing is complete.- No
async
ordefer
: Loads and executes the script immediately, pausing page parsing until execution finishes.
Attribute Details
- Boolean Attribute: The
defer
attribute does not require avalue
. - Applies To: Only used with the
<script>
element.
Conclusion
The defer
attribute helps optimize webpage performance by ensuring scripts run only after the document is fully parsed. This prevents scripts from blocking rendering, leading to faster page loads and a smoother user experience. It is best suited for external scripts that interact with the document structure, making it a best practice for modern web development.
data-*
HTML data attributes enable the storage of custom data on elements, accessible through JavaScript and prefixed with data-. This allows for attaching additional information without impacting the element's functionality.
dir
The dir attribute in HTML indicates the text direction of an element's content, using values like ltr for left-to-right and rtl for right-to-left, influencing how languages are displayed.