<script>...</script> tag, it must pause the DOM building process to fetch and execute the script. This is particularly impactful for external scripts (
<script src=”...”>), potentially degrading the overall user experience.
Scripts placed in the <head> section of a webpage directly impact loading metrics like Largest Contentful Paint (LCP), as the HTML parsing process is paused until the script is fetched and executed.
Placing scripts at the end of the <body> tag is a simple solution. This approach allows the HTML parsing process to complete uninterrupted, and the script is executed only after the DOM is ready, not affecting loading metrics like Page Load Time (PLT) and LCP.
Challenges of placing scripts at the end of the body
However, this technique has limitations. It’s only effective if the script can execute after the DOM is ready. Additionally, script fetching time, influenced by network conditions and script size, can delay execution.
Optimizing with defer and async
<script defer src=”your-script.js”></script>
<script async src=”your-script.js”></script>
Both attributes prevent blocking the DOM building process, supported by most modern browsers (caniuse.com/script-async).
What is “defer”?
defer attribute allows the script to load in the background and execute when the DOM is fully built, improving performance by fetching the script while parsing the HTML.
What is “async”?
async attribute makes the script independent, allowing it to fetch without blocking HTML parsing and execute at any point relative to the DOM’s readiness.
Defer ensures HTML parsing is never blocked, while async loads scripts independently.