====== Script tag placement ====== The ** ===== Placing the Script in the Body ===== ;;;Placing the **
This approach helps prevent the script from blocking the rendering of the page, similar to using the **defer** attribute in the **
**.
===== Async vs Defer =====
Both the **async** and **defer** attributes are used with the **
==== Defer ====
* **Download**: Like async, the script is downloaded asynchronously, in parallel with the HTML parsing.
* **Execution**: Unlike async, the script execution is deferred until after the HTML has been fully parsed.
* **Order**: Scripts with the defer attribute are executed in the order they appear in the HTML, maintaining dependencies between scripts.
* **Use Case**: Use defer when the script relies on the full DOM structure and should be executed after the HTML is fully parsed, or when the order of script execution matters.
Example:
==== Comparison ====
**Use async when the script is completely independent**, and it doesn't matter when it runs. Since it runs as soon as it's downloaded, it can interfere with page rendering if it's a large script or if there's a slow network. \\ \\
**Use defer when you need the script to run after the HTML is parsed**, or when you have multiple scripts that need to be run in a specific order. Since it waits for the HTML to be parsed, it is often more user-friendly as it doesn't block rendering.