Home > Web Front-end > JS Tutorial > Detailed introduction to JavaScript asynchronous loading (with code)

Detailed introduction to JavaScript asynchronous loading (with code)

不言
Release: 2019-04-12 11:54:02
forward
2446 people have browsed it

This article brings you a detailed introduction to JavaScript asynchronous loading (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Before talking about this question, let’s start with another high-frequency interview question,

What did our web page go through from the beginning of parsing to the completion of page rendering?

1. Create a document object and start parsing the page. At this time, document.readyState = 'loading'

2. When encountering the css file introduced by the link tag, create a thread and load the css asynchronously. Continue Parse the document

3. When encountering an external script introduced by the script tag, if the attribute of the script tag is set to defer or async, create a thread to load js asynchronously, otherwise load js synchronously (blocking the parsing of dom) and continue parsing. Document (executed after the async script is loaded)

4. When encountering img and other tags that need to load resources, parse the dom tag normally, load src asynchronously, and continue to parse the document

5. The document parsing is completed , document.readyState = 'interactive', all defer scripts are executed in order, and the document will trigger the DOMContentLoaded event, marking the program's conversion from the synchronous script execution phase to the event-driven phase

6. When all async scripts are loaded and After execution, img is loaded, document.readyState = 'complete', window triggers load event.

7. From now on, user input, network events, etc. will be processed in an asynchronous response. . . . . .

ok, just talking is useless, let’s see if there is only one truth. . .

document.onreadystatechange = () => {
    console.log(document.readyState)
};
document.addEventListener('DOMContentLoaded', () => {
    console.log('DOMContentLoaded')
});
window.onload = () => {
    console.log('load')
};
Copy after login

Note that the DOMContentLoaded event can only be bound with addEventListener

The result is this:

is printed out in order. . .

We mentioned above that only scripts with defer /async set can be loaded asynchronously.

Note that defer is not compatible with some lower version browsers.

async is a W3C standard, but it can only be used when introducing external js files.

Of course, the most common thing we use is to put the script tag after the body, so that it will not block the DOM parsing

There is another situation where dynamically added scripts are also loaded asynchronously. Based on this, we encapsulate a function that loads scripts asynchronously

function loadScript (url, callback) {  // 传入url , 和要执行的回调函数
    const script = document.createElement('script');
    script.type = 'text/javascript';  // 创建一个script标签
    if (script.readyState) {   // 做兼容
        script.onreadystatechange = () => {  // readyState变化触发
            if (script.readyState === 'complete' || script.readyState === 'loaded') { // 兼容
                callback();  // 加载完执行回调            }
        }
    } else {
        script.onload = () => {
            callback();  // 加载完执行回调        }
    }
    script.src = url;
    document.head.appendChild(script);  // 插入head中}
Copy after login

above That’s all the content of js asynchronous loading. Friends are welcome to add

The above is the detailed content of Detailed introduction to JavaScript asynchronous loading (with code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Issues
What are JavaScript hook functions?
From 1970-01-01 08:00:00
0
0
0
What is JavaScript garbage collection?
From 1970-01-01 08:00:00
0
0
0
c++ calls javascript
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template