JavaScript script tag synchronous asynchronous loading process

synchronous loading

Synchronous mode, also known as blocking mode, will prevent the browser's subsequent processing and stop subsequent parsing. Only when the current loading is completed can the next step be performed.

<script src="http://xxx/script.js"></script>
<!--所以一般建议把<script>标签放在<body>结尾处,这样尽可能减少页面阻塞。-->

asynchronous loading

Asynchronous loading is also called non-blocking loading. While the browser is downloading and executing js, it will continue to process subsequent pages. There are three main ways.

defer

<script src="http://xxx/script.js" defer></script>
 <!--要等dom文档全部解析完(dom树生成)才会被执行。-->

async

<script src="http://xxx/script.js" defer></script>
 <!--加载完就执行;async只能加载外部脚本,不能写js到标签里。-->

Script DOM Element

This method is <script>to create a script element with js in the tag of the page and insert it into the document.
The following is an asynchronously loaded js file that encapsulates function compatibility, and the functions in the file can be executed on demand (load on demand)

<script>

        function loadScript(url,callback){
      
      
            //url是按需加载的js文件
            //callback是按需加载的js文件中某个函数
            // 1. 创建一个script标签
            var script = document.createElement('script');    
            // 处理ie的兼容
            if(script.readyState){
      
      
                script.onreadystatechange = function(){
      
      
                    // 如果script已经下载完成
                    if(script.readyState == 'complete' || script.readyState == 'loaded'){
      
      
                        callback();
                    }
                }
            }else{
      
      
                // 监听script的下载的状态 当状态变为下载完成后 再执行callback
                script.onload = function(){
      
      
                    callback();
                }
            }
            //在后面引入的目的是如果在IE上如果下载太快(比读程序还快)
            //IE的readystatechange 事件检测状态码的时候,它早已经从loading变成complete或者loaded(以极快的速度加载完了文件,你还没来得及检测)
            // 那你再检测它就不会变了,它一直都是complete或者loaded
            //这个时候就是马后炮了,检测也没用了。
            // 2. 给script标签添加src 引入一个js文件
            script.src = url;
            // 3. 追加到body
            document.body.appendChild(script);
        }
    </script>

Supplement: three states of document

document.readyState === "loading" //表示document仍在加载
document.readyState === "interactive"//文档已经完成加载,文档已被解析,但是诸如图像,样式表和框架之类的子资源仍在加载。
interactive //活跃状态,dom树绘制完成
document.readyState === "complate" T文档和所有子资源已完成加载。状态表示 [load]

Guess you like

Origin blog.csdn.net/weixin_44000173/article/details/126119783