Table of Contents
How async works
How defer works
When to use which?
One more thing: no attribute
Home Web Front-end HTML Tutorial What is the difference between async and defer for script tags?

What is the difference between async and defer for script tags?

Jul 29, 2025 am 04:21 AM

When using async, the script is downloaded asynchronously and executed immediately, and the execution order is not guaranteed. It is suitable for independent scripts; 2. When using defer, the script is downloaded asynchronously but delayed until the HTML parsing is completed and executed in sequence, which is suitable for scripts that rely on DOM or need to be executed in sequence; 3. If there is no attribute, the script will block HTML parsing, affecting performance; therefore, use async for non-critical scripts and use defer for key logic.

What is the difference between async and defer for script tags?

When you add a <script></script> tag to an HTML document, the browser normally downloads and executes the script immediately, which can block HTML parsing and slow down page loading. To improve performance, HTML provides two attributes — async and defer — that change how external scripts are loaded and executed. While both help avoid blocking the page, they work differently.

What is the difference between async and defer for script tags?

How async works

When you use async :

 <script src="script.js" async></script>
  • The script is downloaded in the background while the HTML continues to parse.
  • As soon as the script finishes downloading, parsing stops , and the script is executed immediately.
  • After execution, HTML parsing resumes.

Key behavior :

What is the difference between async and defer for script tags?
  • Execution order is not guaranteed . If you have multiple async scripts, they run as soon as they're ready, which might not be in the order they appear in the HTML.
  • Best for scripts that are independent (like analytics or ads) and don't rely on the DOM or other scripts.

Example: Script A is smaller and downloads faster than Script B, even if B comes first in the HTML — A will run first.

How defer works

When you use defer :

What is the difference between async and defer for script tags?
 <script src="script.js" defer></script>
  • The script is downloaded in the background , like with async .
  • But execution is delayed until the HTML parsing is completely finished .
  • Scripts with defer execute in order , right after parsing ends but before the DOMContentLoaded event.

Key behavior :

  • Scripts run in the order they appear in the HTML.
  • The DOM is fully constructed by the time they run, so it's safe to manipulate elements.
  • Ideal for scripts that need the full DOM or depend on other scripts.

Example: If you have multiple defer scripts, they download in any order but execute in sequence after the page finishes parsing.

When to use which?

  • Use async for:

    • Independent scripts (eg, Google Analytics, third-party widgets).
    • You don't care when they run, as long as they don't block rendering.
    • Faster execution as soon as possible — even before the page is fully parsed.
  • Use defer for:

    • Scripts that rely on the DOM or other scripts.
    • You need them to run in a specific order.
    • Main application logic that should run after the page is ready.

One more thing: no attribute

If you use neither async nor defer :

  • The browser stops parsing HTML while it downloads and runs the script.
  • This can significantly delay page rendering, especially if the script is large or slow to load.

In summary :

Feature async defer No attribute
Download timing In parallel with HTML In parallel with HTML Blocks HTML parsing
Execution timing As soon as downloaded After HTML parsing completes Immediately when reached
Execution order Not guaranteed Preserved (as in HTML) As in HTML
DOM available? Not necessary Yes Depends

So, if you want scripts to load fast without blocking, but don't need them in order — use async .
If you need scripts to run in order and after the page is ready — use defer .

Basically, defer is safer for most site-critical scripts, while async is best for independent, non-essential ones.

The above is the detailed content of What is the difference between async and defer for script tags?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1504
276
Implementing Native Lazy Loading for Images in HTML Implementing Native Lazy Loading for Images in HTML Jul 12, 2025 am 12:48 AM

Native lazy loading is a built-in browser function that enables lazy loading of pictures by adding loading="lazy" attribute to the tag. 1. It does not require JavaScript or third-party libraries, and is used directly in HTML; 2. It is suitable for pictures that are not displayed on the first screen below the page, picture gallery scrolling add-ons and large picture resources; 3. It is not suitable for pictures with first screen or display:none; 4. When using it, a suitable placeholder should be set to avoid layout jitter; 5. It should optimize responsive image loading in combination with srcset and sizes attributes; 6. Compatibility issues need to be considered. Some old browsers do not support it. They can be used through feature detection and combined with JavaScript solutions.

Implementing Responsive Images with the HTML srcset and sizes Attributes Implementing Responsive Images with the HTML srcset and sizes Attributes Jul 12, 2025 am 12:15 AM

srcset and sizes are key properties for HTML implementation of responsive images. srcset provides multiple image sources and their width or pixel density, such as 400w and 800w, and the browser selects the appropriate image accordingly; sizes defines the display width of the image under different screen widths, such as (max-width: 600px)100vw, 50vw, so that the browser can more accurately match the image size. In actual use, you need to prepare multi-size pictures, clearly named, design layout in accordance with media query, and test the performance of the equipment to avoid ignoring sizes or unit errors, thereby saving bandwidth and improving performance.

Creating Hyperlinks for Navigation with the HTML a Tag Creating Hyperlinks for Navigation with the HTML a Tag Jul 11, 2025 am 03:03 AM

Using HTML tags, you can use the href attribute to realize page jump, open new windows, positioning within pages and email and phone link functions. 1. Basic usage: Specify the target address through href, such as accessing a web page; 2. Open a new window: add target="_blank" and rel="noopener" attributes; 3. Jump within the page: combine id and # symbol to achieve anchor point positioning; 4. Email phone link: use mailto: or tel: protocol to trigger system applications.

What are the differences and use cases for html textarea and input type text? What are the differences and use cases for html textarea and input type text? Jul 12, 2025 am 02:48 AM

The main difference is that textarea supports multiple lines of text input, while inputtext is only available in a single line. 1. Use inputtype="text" to be suitable for short and single-line user input, such as username, email address, etc., and can set maxlength to limit the number of characters. The browser provides automatic filling function, making it easier to uniformly style across browsers; 2. Use textarea for scenarios that require multiple lines of input, such as comment boxes, feedback forms, support line breaks and paragraphs, and can control the size through CSS or disable the adjustment function. Both support form features such as placeholders and required fills, but textarea defines the size through rows and cols, and input uses the size attribute.

The `` vs. `` in HTML The `` vs. `` in HTML Jul 19, 2025 am 12:41 AM

It is a block-level element, used to divide large block content areas; it is an inline element, suitable for wrapping small segments of text or content fragments. The specific differences are as follows: 1. Exclusively occupy a row, width and height, inner and outer margins can be set, which are often used in layout structures such as headers, sidebars, etc.; 2. Do not wrap lines, only occupy the content width, and are used for local style control such as discoloration, bolding, etc.; 3. In terms of usage scenarios, it is suitable for the layout and structure organization of the overall area, and is used for small-scale style adjustments that do not affect the overall layout; 4. When nesting, it can contain any elements, and block-level elements should not be nested inside.

How to create a simple popup or modal with HTML, CSS, and JS? How to create a simple popup or modal with HTML, CSS, and JS? Jul 12, 2025 am 02:42 AM

To achieve a basic pop-up effect, you need to follow the following steps: 1. Structure: Use HTML to create trigger buttons, mask layer and pop-up content area; 2. Style: Set default hidden, centered layout, mask background and close button styles through CSS; 3. Interaction: Use JavaScript to bind click events to control pop-up display and hide, and can expand the ESC key closing function; 4. Optimization: Add CSS animation to improve user experience. The entire process does not require a third-party library, which is suitable for quickly realizing basic pop-up functions.

Working with Reusable Content Fragments Using the HTML template Tag Working with Reusable Content Fragments Using the HTML template Tag Jul 11, 2025 am 03:19 AM

Tags are a tag introduced by HTML5 to define reusable content fragments. They are not rendered immediately, but can be dynamically inserted through JavaScript. The usage process includes: 1. Defining the template; 2. Cloning the content; 3. Inserting the DOM. For example, get the template through document.getElementById, call cloneNode(true) and insert the page. When dynamically filling the data, content binding can be achieved by operating the cloned DOM elements, which is suitable for building product lists, user cards and other components. When using it, be careful not to directly access template sub-elements, avoid ID conflicts, handle style scopes, and can also create encapsulation components with WebComponents.

What are web workers and how do they relate to HTML? What are web workers and how do they relate to HTML? Jul 12, 2025 am 03:03 AM

Webworkers are independent threads running in the browser background, used to perform time-consuming tasks without blocking the user interface. They are implemented through JavaScript files and are started by scripts in HTML pages, but once run, they are separated from the main thread. 1. Webworkers cannot directly access the DOM to ensure page stability; 2. They realize secure communication with the main thread through postMessage() and onmessage; 3. It is suitable for processing CPU-intensive tasks such as images, complex computing, data analysis; 4. It supports some APIs such as setTimeout, fetch and IndexedDB; 5. When using it, you need to pay attention to debugging difficulties, memory usage, cross-domain restrictions and other issues.

See all articles