Table of Contents
Draw a few pictures and briefly explain
Normal script
defer
async
Recommended application scenarios
Home Web Front-end HTML Tutorial Async and defer usage in script tags

Async and defer usage in script tags

Oct 18, 2017 am 09:27 AM
async defer script

The

script tag is used to load scripts and execute scripts. It can be said to be a very important tag in front-end development.
If you use the script script directly, html will load and execute the script in order. During the script loading & execution process, subsequent DOM## will be blocked. #render.

Nowadays, everyone is accustomed to referencing various third-party scripts in the page. If the third-party service provider has some minor problems, such as delay, the page will be blank.

Fortunately,
script provides two ways to solve the above problems, async and defer. These two attributes make script Neither will block the rendering of DOM. But since there will be two attributes, it means that there must be a difference between these two attributes.

defer

If the

script tag sets this attribute, the browser will download the file asynchronously and will not affect the subsequent DOM rendering; If there are multiple
script tags with defer set, all script will be executed in order;
deferThe script will be executed after the document is rendered and before the DOMContentLoaded event is called.

We made a test page, which contains the loading of two

script tags, and adds the defer logo to them.
P.S. In order to be more intuitive, we added a delay of 1s to script1.js and 2s to script2.js Delay.
Async and defer usage in script tagsThe picture below is the page loading process&
scriptThe output sequence of the script. It is not difficult to see that although the loading time of
script1 is shorter than that of script2, due to the limitation of defer, it can only wait for the previous script to be executed. can only be executed later. The setting of
Async and defer usage in script tags
Async and defer usage in script tags##async

async

will make the script script asynchronous Loading and executing async
when allowed will not be executed in the order of script on the page, but whoever loads it first will execute it.

We modified the test page as follows:


We got the following results. There is no change in the page loading time. After all, they are all asynchronously loaded scripts. Async and defer usage in script tagsBut we can see a small detail. The triggering of the

DOMContentLoaded event is not affected by the asyncscript loading. Before the script is loaded, DOMContentLoaded has been triggered.
Async and defer usage in script tags
Async and defer usage in script tags
Async and defer usage in script tags

We then modify the test page. Load a script script without delay so that the script can be loaded immediately.
We want to test if the async script loads quickly enough, whether it will be executed before DOMContentLoaded (This experiment is based on async's description of the "execution if allowed" argument ).
At the same time, in order to ensure the stability of the test, we added thousands of empty p nodes after the introduction of the script script to extend the rendering time of the document.
Async and defer usage in script tags
The execution result is as expected. If async is given a certain amount of time, it is possible to execute it before the DOMContentLoaded event.
Async and defer usage in script tags
P.S. From the flame graph in the upper left corner of the picture above, we can also see that there are multiple segments of blue (Update: I was confused when I wrote it at night, purple The one is rendering, the blue one is parsing) document rendering. And the order of Console below.
Explanation Indeed, the execution of async is executed after loading is completed, unlike defer which has to wait for all scripts to be loaded and executed in order.

Draw a few pictures and briefly explain

There are many similar pictures on the Internet, but they are basically just examples using a script
It is too shabby. So let’s get a deluxe version and draw a Gantt chart when loading multiple scripts
Just like the major mobile phone manufacturers in recent years, they all like to have an X+X plus when they release new phones

Use four different colors to indicate the meaning of each
Async and defer usage in script tags

Normal script

During the document parsing process, if you encounter a script script , it will stop the rendering of the page and download it (but it will not affect the subsequent parsing, parsing and rendering are two different things).
The download of resources is carried out during the parsing process. Although the script1 script will be loaded quickly, the script2 in front of it is not loaded & executed, so it only It can be in a suspended state, waiting for script2 to finish executing before executing it.
When both scripts are executed, the page will continue to be rendered.
Async and defer usage in script tags

defer

When parsing the document, if a script with defer is encountered, it will be downloaded in the background, but the document will not be blocked. Rendering, when the page parsing & rendering is completed.
It will wait until all defer scripts are loaded and executed in order. After the execution is completed, the DOMContentLoaded event will be triggered.
Async and defer usage in script tags

async

asyncThe script will be executed after loading.
asyncThe loading of the script is not included in the DOMContentLoaded event statistics, which means that both situations in the figure below are possible

Async and defer usage in script tags
Async and defer usage in script tags

defer

If your script code depends on the DOM element in the page (whether the document is rendered Completed), or depended on by other script files.
Example:

  1. Comment box

  2. Code syntax highlighting

  3. polyfill.js

async

If your script doesn’t care about the DOM elements in the page ( Whether the document has been rendered), and no data required by other scripts will be generated

The above is the detailed content of Async and defer usage in 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

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.

Undress AI Tool

Undress AI Tool

Undress images for free

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)

Is async for es6 or es7? Is async for es6 or es7? Jan 29, 2023 pm 05:36 PM

async is es7. async and await are new additions to ES7 and are solutions for asynchronous operations; async/await can be said to be syntactic sugar for co modules and generator functions, solving js asynchronous code with clearer semantics. As the name suggests, async means "asynchronous". Async is used to declare that a function is asynchronous; there is a strict rule between async and await. Both cannot be separated from each other, and await can only be written in async functions.

What does script mean? What does script mean? Aug 29, 2023 pm 02:00 PM

Script means script or script. In film, television, drama and other art forms, script is used to describe the dialogue, actions and scenes of characters, as well as the development and structure of the story. Script writing requires certain skills and experience, and it should be vivid and powerful, capable of attracting the audience's attention and conveying the emotions and themes of the story. Scripts are particularly important in the film and television industries. They are the basis of creation and determine the storyline, character development and dialogue content of the film. Script is an important tool for artists to create and express themselves.

How vue3+async-validator implements form validation How vue3+async-validator implements form validation May 11, 2023 am 09:55 AM

Building a vue3 project Before creating a project, the first thing we need to explain is that the version we use is Nodejs: v17.5.0pnpm: 7.0.0Vue: 3.2.25. First, we Vite creates a vue3 project demo named FormValidate. Enter the command pnpmcreateviteFormValidate on the command line and press Enter, then select vue and continue to press Enter, indicating that we have initially created the FormValidate (form validation) project. According to the command line prompts, we enter the project root directory, and then use the command pnpminstall to install the dependencies required for the project. Of course Using pnpm here is better than n

what is script what is script Oct 12, 2023 am 10:04 AM

In the field of computer science, "script" usually refers to a scripting language or script file. A scripting language is an interpreted programming language commonly used for tasks such as automation, batch processing, and rapid prototyping.

What is defer keyword in Go language? What is defer keyword in Go language? Jun 11, 2023 am 09:10 AM

What is the defer keyword in Go language? When writing programs, we often need to perform some cleanup or resource release work after a certain function or method is executed. At this time, the Go language provides a convenient mechanism. By using the defer keyword, these cleanup or resource release tasks can be postponed until the function or method returns. The defer keyword is a syntax sugar that is parsed at compile time. It defers the call of a function or method until the current function or method returns.

How to use async/await to handle asynchronous operations in Vue How to use async/await to handle asynchronous operations in Vue Jun 11, 2023 am 09:18 AM

How to use async/await to handle asynchronous operations in Vue With the continuous development of front-end development, we need to handle more complex asynchronous operations in Vue. Although Vue already provides many convenient ways to handle asynchronous operations, in some cases, we may need to use a simpler and more intuitive way to handle these asynchronous operations. At this time, async/await becomes a very good choice. What is async/await? In ES2017, async and

How to use Python async module How to use Python async module May 30, 2023 pm 11:43 PM

Coroutine: Coroutine, also known as micro-thread, is a context switching technology in user mode. In short, it is actually a thread to implement code blocks to switch between executions. Python's support for coroutines is implemented through generators. In the generator, we can not only iterate through the for loop, but also continuously call the next() function to obtain the next value returned by the yield statement. But Python's yield can not only return a value, it can also receive parameters sent by the caller. 1. What is a generator? In Python, this mechanism of looping and calculating at the same time is called a generator: gene

How to solve scripterror How to solve scripterror Oct 18, 2023 am 09:44 AM

Solutions to scripterror include checking syntax, file path, checking network connection, browser compatibility, using try-catch statements, using developer tools for debugging, updating browsers and JavaScript libraries, or seeking professional help. Detailed introduction: 1. Check for syntax errors: Script Error may be caused by syntax errors in JavaScript code. Use developer tools to check the code and fix syntax errors. Make sure that the brackets, quotation marks, semicolons, etc. in the code are correct. etc.

See all articles