Facebook Pixel

async and defer Best Practices

Best practices for script loading with async and defer.

async and defer Best Practices

1. Use defer for Most Scripts

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

Non-blocking, ordered, executes after DOM is ready. Best for app logic and dependencies.

2. Use async for Independent Scripts

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

Does not depend on other scripts or the DOM. Downloads and executes independently.

3. Put defer Scripts in the Head

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

This starts the download early while deferring execution. Faster than putting at the bottom of body.

4. Do Not Use async for Dependent Scripts

async does not guarantee order. If script B depends on A, use defer for both.

5. Use type="module" (Automatic defer)

ES modules are deferred by default:

<script type="module" src="app.js"></script>

No need for defer. It is automatic.

The Takeaway

Best practices: use defer for most scripts (ordered, non-blocking), async for independent scripts (analytics), put defer scripts in the head (early download), do not use async for dependent scripts (unordered), and use type='module' (defer is automatic).

defer. It is non-blocking, executes in order, and runs after the DOM is ready. Use async only for independent scripts like analytics and ads.

In the <head>. This starts the download early (in parallel with HTML parsing) while deferring execution until after parsing. This is faster than placing scripts at the bottom of <body>.

Yes. <script type='module'> is automatically deferred. You do not need to add the defer attribute. The script downloads in parallel and executes after parsing.

No. async does not guarantee execution order. If script B depends on A, use defer for both. defer guarantees order.

defer in head starts the download earlier (in parallel with parsing) while deferring execution. Scripts at the bottom start downloading later (after most of the HTML is parsed). defer in head is faster.

Ready to master React completely?

Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.

Please Login.
Please Login.
Please Login.
Please Login.