Scripts: async, defer

Scripts: async, defer

Async and defer in JavaScript Script Tags

When adding JavaScript files to an HTML document using the <script> tag, async and defer control how and when the script is downloaded and executed.

1. Default Behavior (Without async or defer)

<script src="script.js"></script>

🔹 The browser stops parsing HTML when it encounters this script, downloads and executes it immediately, then continues rendering the rest of the page.
🔹 This can block the page from rendering if the script takes time to load.

2. async Attribute

<script src="script.js" async></script>

🔹 The script downloads in parallel while the HTML continues to be parsed.
🔹 Once downloaded, the script executes immediately, pausing HTML parsing.
🔹 Best for: Independent scripts that don’t depend on other scripts (e.g., analytics, ads).

Example Use Case:

<script src="https://www.googletagmanager.com/gtag/js" async></script>

✅ Good for scripts that don’t modify the DOM or rely on other scripts.

3. defer Attribute

<script src="script.js" defer></script>

🔹 The script downloads in parallel while the HTML is being parsed.
🔹 The script executes only after the entire HTML document is loaded.
🔹 Best for: Scripts that depend on the full DOM structure (e.g., adding event listeners).

Example Use Case:

<script src="main.js" defer></script>

✅ Ensures main.js executes only after the page is fully loaded.

4. Key Differences:

AttributeDownloadExecutionBlocks HTML Parsing?Order of Execution
❌ NoneImmediatelyImmediately✅ YesIn order of appearance
asyncIn parallelImmediately after download❌ NoOrder is unpredictable
deferIn parallelAfter the HTML is fully parsed❌ NoIn order of appearance

5. When to Use Which?

Use CaseBest Option
Analytics, tracking scriptsasync
DOM-dependent scripts (e.g., event listeners, UI updates)defer
Scripts that modify the page immediately (jQuery, inline scripts)No attribute
Multiple scripts that need to run in orderdefer

6. Best Practice for Performance

For better performance and non-blocking execution, place scripts at the end of <body> or use defer:

<script src="app.js" defer></script>

Conclusion

  • Use async when script execution order doesn't matter (e.g., analytics, ads).
  • Use defer when scripts depend on the full DOM and need to run in order.
  • Avoid blocking scripts without async  defer unless necessary.

Would you like an example of using these in a real project? 

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close