Home > Web Front-end > JS Tutorial > How to load js asynchronously? Introduction to the method of loading js asynchronously

How to load js asynchronously? Introduction to the method of loading js asynchronously

青灯夜游
Release: 2019-01-05 10:33:36
forward
3082 people have browsed it

How to load js asynchronously? This article will introduce to you three methods of asynchronously loading js. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. [Video tutorial recommendation: JavaScript video tutorial]

js loading timeline:

It is born based on js The series of things that the browser does in sequence recorded starting from that moment describe the loading sequence, what can be used to optimize, the theoretical basis, memorize it.

1, create Document Object to start parsing the web page. Add Element objects and Text nodes to the document after parsing HTML elements and their text content. At this stage document.readyState = 'loading'. (The document object is generated, and the document status bit changes to loading)

2. When encountering link external css, create a thread to load, and continue to parse the document.

3, When encountering a script external js, and no async or defer is set, the browser loads and blocks, waits for the js to be loaded and executes the script, and then continues to parse the document.

4. When encountering script external js and setting up async and defer, the browser creates a thread to load and continues to parse the document. For scripts with async attributes, they are executed immediately after the script is loaded. (It is prohibited to use document.write() asynchronously)

document.write(): It is very special. It treats the contents as an HTML document and outputs it to the page. But one thing is that sometimes, when you When the entire document is almost parsed, if you use document.write(), all your previous document streams will be cleared, and the document streams in it will be used instead

Example: The entire page only displays a, here The document.write(); here has the function of eliminating the document flow, and even the script is eliminated.

<p style="height:100px;width:100px;background-color:red;"></p>
Copy after login
<script type="text/javascript">
    window.onload = function(){
        document.write(&#39;a&#39;);
    }
</script>
Copy after login

5 When encountering img, etc., first parse the dom structure normally, then the browser loads src asynchronously and continues to parse the document.

6. When the document parsing is completed, document.readyState = 'interactive'.

First parse, then load, and then the status bit changes to interactive (active)

Check the status bit transition:

console.log(document.readyState);
document.onreadystatechange = function(){
     console.log(document.readyState);
}
Copy after login

7 After the document parsing is completed, all scripts set with defer will be executed in order. (Note that it is different from async, but it is also prohibited to use (document.write());

8. The document object triggers the DOMContentLoaded event, which also marks the transition from the synchronous script execution phase to program execution. , converted into an event-driven stage.

Example 1: Print a and complete at the same time, and onDOMContentLoaded is not easy to use. It can only be used if it is bound to addEventListener.

console.log(document.readyState);
document.onreadystatechange = function(){
     console.log(document.readyState);
}
document.addEventListener(&#39;DOMContentLoaded&#39;,function(){
      console.log(&#39;a&#39;);
},false)
Copy after login

Example 2: The difference between window.onload and the following one

$(document).ready(function(){
    //当DOM解析完就执行的部分(不用加载完,加载完是给用户看的,对于我们来说解析完就可以操作了)
    /*它的原理就是interactive和DOMContentLoaded事件*/
})
Copy after login

The difference is: window.onload is loaded as needed, but it can be operated after it is parsed (this is the jQuery method)

Example 3: When placing the script above, it is best to write it like this, do not write onload, never write onload, but the best way is to write it below

<head>
    <meta charset="UTF-8">
    <title>lottery</title>
    <script type="text/javascript">
        document.addEventListener(&#39;DOMContentLoaded&#39;,function(){
            var p = document.getElementsByTagName(&#39;p&#39;)[0];
            console.log(p);
        },false)
    </script>
    script标签写在上面又能处理下面的代码,而且效率还高,因为登高DOM解析完就执行,而不是DOM加载完
</head>
//script标签写在上面又能处理下面的代码,而且效率还高,因为登高DOM解析完就执行,而不是DOM加载完
Copy after login

9. When all async scripts are loaded and executed, and img etc. are loaded, document.readyState = 'complete', the window object triggers the load event.

10, From now on, Process user input, network events, etc. in an asynchronous response mode.
The summary is three points: first generate the document object, which means that js can be run, the second step is that the document is parsed, and the third step is that the document is loaded and executed.


Let’s take a look at three ways to load js asynchronously:

Methods to load js asynchronously:

1), async HTML5 attribute, allows JavaScript code to be loaded asynchronously

<script type="text/javascript" src="05.js" async="async"></script>
Copy after login

2) defer is exclusive to old versions of IE

<script type="text/javascript" defer="defer"></script>
Copy after login

3) Dynamically create script tags (It can solve the problem of compatibility with h5 and lower versions of ie), the code is as follows:

<script type="text/javascript">
            function asyncLoaded(url,callback){
                var script = document.createElement("script");
//                script.src = url;   假如说网速非常好,直接执行完成了,后面就监听不到状态的改变了
                if(script.readyState){
                    script.onreadystatechange = function(){
                        if(script.readyState == "complete" || script.readyState =="loaded"){
//                            执行某个函数
                            callback()
                        }
                    }
                }else{
                    script.onload = function(){
//                        执行某个函数
                        callback()
                    }
                }
                script.src = url;    //异步的过程
                document.head.appendChild(script)    
            }
            asyncLoaded("05.js",function(){
                fn()          //05.js中的函数
            })
        </script>
Copy after login

The above is the entire content of this article, I hope it will be helpful to everyone's learning. For more exciting content, you can pay attention to the relevant tutorial columns of the PHP Chinese website! ! !

The above is the detailed content of How to load js asynchronously? Introduction to the method of loading js asynchronously. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template