Course contentsShow
← Web Development
Lesson 2830 of 2,98250. Third-Party IntegrationsFree lesson

Async and Defer Script Loading

Master async and defer attributes to control when third-party embed scripts execute relative to page load.

Async and Defer Script Loading

You'll learn how async and defer attributes control third-party script execution timing to optimize page performance.

The Problem with Default Script Loading

When a browser encounters a <script> tag without special attributes, it stops everything: HTML parsing halts, the script downloads, then executes immediately. For third-party embeds like analytics or chat widgets, this blocks your page from rendering—creating a frustrating user experience.

Async: Download in Parallel, Execute ASAP

The async attribute tells the browser: "Download this script in the background while parsing HTML, but execute it the moment it finishes downloading—even if the page isn't fully parsed."

<script async src="https://analytics.example.com/track.js"></script>

Use async when: The script is independent and doesn't rely on DOM structure or other scripts. Perfect for analytics that just need to fire as soon as possible.

Caution: Execution order is unpredictable. Multiple async scripts may run in any sequence.

Defer: Download in Parallel, Execute After Parsing

The defer attribute says: "Download in the background, but wait until HTML parsing completes before executing. Then run in document order."

<script defer src="https://widget.example.com/embed.js"></script>

Use defer when: The script needs the full DOM available or must execute in a specific order relative to other deferred scripts.

Real-World Choice

For third-party embeds, defer is usually safer—it won't interrupt rendering and guarantees the DOM exists. Use async only for truly independent tracking pixels or beacons that don't manipulate your page.

Key Takeaway: Use defer for third-party scripts that need DOM access or sequential execution; use async only for fully independent scripts that should fire immediately upon download.