Let's learn about the async and defer attributes in script tags

青灯夜游
Release: 2020-11-11 17:46:40
forward
2579 people have browsed it

Let's learn about the async and defer attributes in script tags

Of course the front end starts with HTML. Let’s talk about the functions and differences when adding async/defer to the script tag.

Everyone knows the truth

We all know that the browser parses HTML and reads it backwards line by line in order. In the traditional In the writing method, when the browser reads <script></script>, it will pause parsing the DOM and immediately start downloading the resources defined in <script></script> , and execute it immediately after the download is completed. Due to such characteristics, JavaScript may start executing before the DOM tree is fully parsed, and programs that need to operate the DOM may not be able to execute correctly, causing many problems; or due to <script></script> Due to the resource download and execution time process, users will be stuck on a white screen, and will have the experience of feeling that the website is too slow to use.

The solution is also very simple. We need to put the <script></script> tags into the last line of to avoid DOM tree parsing. It's not a complete question, but in complex websites, HTML and JavaScript are very large, and you need to wait until the entire DOM tree is loaded before starting to download the resources in <script></script> and read them from the website. There will be an obvious sense of delay when the retrieval is completed until it is operable.

How to solve this problem?

Starting from HTML4, <script></script> has more defer attributes, while HTML5 has more async, both of which are used Help developers control the loading and execution order of resources within <script></script>, and avoid DOM parsing being stuck in resource downloading.

Lets learn about the async and defer attributes in script tags

defer

##defer means Deferred, in The HTML4.01 specification states:

When set, this Boolean attribute will prompt the user agent that the script will not generate any web content (for example, "document.write" will not be generated in JavaScript) , so the user agent can continue parsing and rendering.
In other words, after adding the

defer attribute, the browser will continue to parse and render the screen without loading is stuck; when actually executed, it will be triggered in the order of placement from top to bottom before DOMContentLoaded is executed.

Sounds very convenient, right? But I would like to remind everyone that although the W3C specification says that the

defer attribute will be a Boolean value, previous versions of IE9 were customized, even if written as

Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template