What are defer and async?

The main way to insert JavaScript into HTML is to use

The two properties are described in javascript Advanced Programming (Version 4) as follows:

Async: Optional. Indicates that you should start downloading the script immediately, but you cannot prevent other page actions, such as downloading resources or waiting for other scripts to load. This applies only to external script files. Defer: Optional. Indicates that the script can be deferred until the document is fully parsed and displayed. This applies only to external script files. In IE7 and earlier, you can specify this property for inline scripts as well.

Here’s a picture to illustrate:

Both control the loading and execution order of

The reasons causing

So what is DOMContentLoaded? The DOMContentLoaded event is emitted when an HTML document has been loaded and parsed. After HTML documents are loaded and parsed, DOM (Document Object Model) is generated. If CSS is present, CSSOM (CSS object model) is generated, and then DOM and CSSOM are combined to produce a render tree. According to the render tree, the browser knows the location layout and style of all nodes, so as to draw.

But Javascript can block DOM generation. In traditional writing, when the browser reads

Also, because JavaScript can query the style of any object, it means that JavaScript can’t be executed until CSS parsing is complete, which is when CSSOM is generated.

Although this can be solved by placing

Usage scenarios

1.defer

If defer is included in the

2.async

If async property is present, the script will be executed asynchronously as soon as available. What is similar to defer is that the download will also be performed in the background, but the difference is that DOM parsing will be suspended as soon as the download is complete (if it hasn’t already) and JavaScript will start executing. Therefore, there is no guarantee of the order in which the scripts are executed. Generally used in independent small modules, such as background Logo, page advertising, etc., in order to avoid user experience deteriorates at the same time, as early as possible to produce the effect.

The resources

Script tag async and defer properties DOMContentLoaded