This is the 15th day of my participation in the August More text Challenge. For details, see: August More Text Challenge

This article is the author’s study notes from the first advanced class of Bytedance’s front End Youth Training camp.

Why do ASYNc and Defer are needed?

Before we get into the difference between async and defer, let’s take a look at the following example: If resource 1 takes a long time to load, but resource 2 completes quickly, the user will have to wait a long time to see the page, resulting in a bad user experience. So we need a method to postpone loading resource 1, which is why async and defer are born.

<script src=1. "resources js." "></script>
<script src="Resources 2. Js"></script>
Copy the code
  • Solutions to the above problems

Let the second file be deferred, that is, add the defer property.

<script src=1. "resources js." " defer></script>
Copy the code

The difference between async and defer

1. No async or defer

In this case, the execution order is synchronous, that is, according to the order defined, the first to execute, after the execution of one to execute the next. This is the case when the script tag is at the bottom of the body, and if it is defined in the head it blocks the parsing of the HTML, as shown in the following figure. The loading and execution of the.js script blocks DOM rendering.

2. Only contains the async

Immediately download, do not affect other operations, wait until the download is complete, pause HTML parsing and then execute the script. (Immediately after loading)

3. Only defer

A script that is downloaded immediately, but executes the defer attribute tag after the Html is parsed and the script is loaded.

The similarities between async and defer

  • All are loaded asynchronously.
  • DOM parsing and loading of other resources are not affected.

Execution step diagram

If you want to test these two properties, you can try creating a server with Node and then test the order of output by delaying the return.

The resources

  • The difference between async and defer properties

  • What are the similarities and differences between async and defer?

  • What’s the difference between Script async and defer

  • The difference between async and defer on the script tag