The
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.
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 thescript
script directly,html
will load and execute the script in order. During the script loading & execution process, subsequentDOM## will be blocked. #render.
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.
If theWe made a test page, which contains the loading of twoscript
tag sets this attribute, the browser will download the file asynchronously and will not affect the subsequent
DOMrendering;
If there are multiple
scripttags with
deferset, all
scriptwill be executed in order;
deferThe script will be executed after the document is rendered and before the
DOMContentLoadedevent is called.
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.
The 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
asyncwill make the
We modified the test page as follows:script
script asynchronous Loading and executingasync
when allowed will not be executed in the order ofscript
on the page, but whoever loads it first will execute it.
We got the following results. There is no change in the page loading time. After all, they are all asynchronously loaded scripts. But we can see a small detail. The triggering of the
DOMContentLoaded event is not affected by the async
script loading. Before the script is loaded,
DOMContentLoaded has been triggered.
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.
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.
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
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.
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
async
The script will be executed after loading. async
The loading of the script is not included in the DOMContentLoaded
event statistics, which means that both situations in the figure below are possible
Recommended application scenarios
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:
Comment box
Code syntax highlighting
-
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!

HTML is used to build websites with clear structure. 1) Use tags such as, and define the website structure. 2) Examples show the structure of blogs and e-commerce websites. 3) Avoid common mistakes such as incorrect label nesting. 4) Optimize performance by reducing HTTP requests and using semantic tags.

ToinsertanimageintoanHTMLpage,usethetagwithsrcandaltattributes.1)UsealttextforaccessibilityandSEO.2)Implementsrcsetforresponsiveimages.3)Applylazyloadingwithloading="lazy"tooptimizeperformance.4)OptimizeimagesusingtoolslikeImageOptimtoreduc

The core purpose of HTML is to enable the browser to understand and display web content. 1. HTML defines the web page structure and content through tags, such as, to, etc. 2. HTML5 enhances multimedia support and introduces and tags. 3.HTML provides form elements to support user interaction. 4. Optimizing HTML code can improve web page performance, such as reducing HTTP requests and compressing HTML.

HTMLtagsareessentialforwebdevelopmentastheystructureandenhancewebpages.1)Theydefinelayout,semantics,andinteractivity.2)SemantictagsimproveaccessibilityandSEO.3)Properuseoftagscanoptimizeperformanceandensurecross-browsercompatibility.

A consistent HTML encoding style is important because it improves the readability, maintainability and efficiency of the code. 1) Use lowercase tags and attributes, 2) Keep consistent indentation, 3) Select and stick to single or double quotes, 4) Avoid mixing different styles in projects, 5) Use automation tools such as Prettier or ESLint to ensure consistency in styles.

Solution to implement multi-project carousel in Bootstrap4 Implementing multi-project carousel in Bootstrap4 is not an easy task. Although Bootstrap...

How to achieve the effect of mouse scrolling event penetration? When we browse the web, we often encounter some special interaction designs. For example, on deepseek official website, �...

The default playback control style of HTML video cannot be modified directly through CSS. 1. Create custom controls using JavaScript. 2. Beautify these controls through CSS. 3. Consider compatibility, user experience and performance, using libraries such as Video.js or Plyr can simplify the process.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Dreamweaver Mac version
Visual web development tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
