Front-end daily practice <async and defer>

We know that the execution of js code is from top to bottom , so if the code is executed somewhere, it may be blocked, preventing the code below from continuing to execute

let's discuss asyncanddefer

Attributes related to the execution order of the script tag:

  • async
    • Do not block the rendering of the page, execute the code in js immediately after getting the js file
  • defer
    • Does not block the execution of the code, does not execute immediately after the js file is obtained, and executes the code in the js after the page rendering is completed
  • leave blank
    • Block page rendering, get the js file and execute the file in js before continuing to execute the code

It's useless to say more, just watch the demo

Here we introduce a js file in an html file and write the script tag before the span tag

A delay is performed when the code in the js file acts, and a p tag is added to the page

var start = Date.now();
while(Date.now() - start < 2000){
    
    }//这里延时2s

var p = document.createElement('p');
p.innerText = 'OK'
document.body.appendChild(p);

image-20220614170244106

When we do not set the async or defer attribute, the page is like this, first execute the code in the js file (delay 2s and then add the p tag to the page), and then continue to execute the rendering page downwards, so the process打印ok->页面渲染

image-20220614170528507

When the attribute is set to async, the rendering of the page will not be blocked (the code continues to execute downward), and the code in the file will be executed after the js file is obtained (delay 2s and then add the p tag to the page), and then continue to execute downward

the process is页面渲染->打印ok->页面渲染

image-20220614170628579

When the property is set to defer, the rendering of the page will not be blocked (the code continues to execute downwards), and the code in the file will not be executed after the js file is obtained, and the code in the js file will be executed after all the pages are rendered.

the process is页面渲染->打印ok

image-20220614170950313

Guess you like

Origin blog.csdn.net/Laollaoaolao/article/details/125283521