Home >Web Front-end >JS Tutorial >Analysis of browser asynchronous loading in JavaScript

Analysis of browser asynchronous loading in JavaScript

不言
不言Original
2018-08-06 17:04:071503browse

The content of this article is about the analysis of browser asynchronous loading in JavaScript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

When we first learned js, we should know that js is single-threaded and loads synchronously, which will block the loading line of html and css (because js can modify html and css)

Disadvantages of js synchronous loading: There is no need to block the document in the loading tool method. Excessive js loading will affect the page efficiency. Once the network speed is not good, the entire website will wait for js to load without proceeding. Subsequent rendering and other work.

Some tools and methods in js need to be loaded on demand. Do you need to load them? Do you need to load them? ? ? At this time we need to load js asynchronously.

Three options for JavaScript asynchronous loading.

1. Defer is loaded asynchronously, but it will not be executed until all DOM documents are parsed. Only IE can be used, or you can write all the code internally

 <script type = "text/javascript" src = "tools.js"  defer = "defer"></script>
<script defer = "defer">
console.log("a");
</script>

2. async asynchronous loading, executed after loading. async can only load external scripts, and cannot write js in the script tag

 <script type = "text/javascript" aysnc = "aysnc"></script>

The above two methods will not block the page when executed

In order to solve the browser compatibility issue? ? If the two methods 1, 2 and 2 are loaded at the same time, it will cause code overlap and conflict in the execution order, so the third method is introduced. Common method

3. Create a script, insert it into the DOM, and callBack after the loading is completed. ,

 var script = document.createElement(&#39;script&#39;);
 script.type = "text/javescript";
 script.src = "demo.js";
// 此时就会加载src地址里面的东西
// 此时会有一个灯塔模式,灯塔模式会产生一个img属性,用来存放地址的加载
document.head.appendChild(script);  //----此时就会在页面上展示js里面的内容

When we write a test function in the external js file

var script = document.createElement(&#39;script&#39;);
script.type = "text/javascript";
script.src = "demo.js";
test();
document.head.appendChild(script);

The external demo.js file will not be displayed here, there is a test function in it. The results are as follows:

#When the test function is executed, it takes time to load. When the test is executed, it has not been loaded yet. So it will show that test is not defined. How do we solve this problem?

First we will think of the onload event.

script.onload : The compatibility is very good, Safari chrome firefox opera is compatible;

 script.onload = function(){
                                test();
                            }

But IE does not have an onload event for script. IE has its own method: script.readyState.

script.readyState: There is a status code (readyState) on IE's script, and the verification of the status code is used to determine whether the loading is complete. In IE, the script tag has a readyStatechange event. This event listens for an event that is triggered when the script.readyState value changes.

(script.readyState == "complete" || script.readyState == "loaded" means that the parsing is completed.)

script.onreadystatechange = function(){
      if(script.readyState == "complete" || script.readyState == "loaded"){
                  callback(); //回调函数:当满足一定条件才可以被执行
              }
                  }

Finally, we encapsulate the function to realize our on-demand loading function.

 function loadScript(url,callback){
                        var script = document.createElement(&#39;script&#39;);
                        script.type = "text/javascript";
                        if(script.readyState){
                            script.onreadyStatechange = function(){
                                if (script.readyState == "loaded" || script.readyState == "complete") {
                                    obj[callback]();
                                }
                            }    
                        }else{
                            script.onload = function(){
                                obj[callback]();
                            }
                        }
                        script.src = url;
                        document.head.appendChild(script);
                    }

                    loadScript(&#39;demo.js&#39;,&#39;test&#39;);

Recommended related articles:

js tutorial - array loop deletion error implementation and solution

[Javascript] zepto source code Callback analysis

The above is the detailed content of Analysis of browser asynchronous loading in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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