DEV Community

Anjan Karmakar
Anjan Karmakar

Posted on

2

Describe the difference between `<script>`, `<script async>` and `<script defer>` for Optimal Website Performance

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!

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Cloudinary image

Video API: manage, encode, and optimize for any device, channel or network condition. Deliver branded video experiences in minutes and get deep engagement insights.

Learn more

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay