Describe the difference between `<script>`, `<script async>` and `<script defer>` for Optimal Website Performance
Anjan Karmakar
Posted on May 14, 2024
Ever wondered how to optimize JavaScript loading on your web pages? The answer lies in understanding the different ways to include scripts using the <script>
tag. Here's a breakdown:
1. <script>
(Default):
- Blocks HTML parsing until the script is downloaded and executed.
- Use this for critical scripts that the page relies on to render initially.
2. <script async>
:
- Downloads the script in parallel with HTML parsing.
- Executes the script as soon as it's available, potentially before HTML parsing finishes.
- Order of execution isn't guaranteed.
- Ideal for non-critical scripts like analytics that don't depend on the DOM being fully built.
3. <script defer>
:
- Downloads the script in parallel with HTML parsing.
- Waits for the HTML to be fully parsed before executing the script, but before the DOMContentLoaded event fires.
- Scripts execute in the order they appear in the HTML.
- Use this for scripts that rely on the DOM being fully available, like manipulating page elements.
Key Takeaways:
async
for independent, non-critical scripts.defer
for DOM-dependent scripts that preserve order.- Both improve performance by allowing parallel parsing.
- Not for critical rendering scripts!
Bonus Tip: Avoid document.write()
with async
or defer
scripts.
By understanding these options, you can ensure your website loads faster and delivers a smoother user experience!
💖 💪 🙅 🚩
Anjan Karmakar
Posted on May 14, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.