Home  >  Article  >  Web Front-end  >  Sample code sharing for JavaScript non-blocking loading performance optimization

Sample code sharing for JavaScript non-blocking loading performance optimization

黄舟
黄舟Original
2017-03-16 15:15:371269browse

JavascriptPerformance in the browser can be said to be the most important usability issue that front-end developers face.

Among Yahoo's Yslow 23 rules, one of them is to put JS at the bottom . The reason is that, in fact, most browsers use a single process to handle multiple tasks such as UI and UpdateJavascript running, and only one task can be executed at the same time. How long the Javascript is running, then how long it waits before the browser becomes idle to respond to user interaction.

At a basic level, this means that the appearance of the 3f1c4e4b6b16bbbd69b2ee476dc4f83a tag causes the entire page to wait for the script to be parsed and run. Regardless of whether the actual JavaScript code is inline or contained in an unrelated external file, the page download and parsing process must stop and wait for the script to complete this processing before continuing. This is an essential part of the pagelifecycle because the script may modify the page content while running. A typical example is document.write()function, for example:

 1 <html>
 2   <head>
 3     <title>Script Example</title>
 4   </head> 
 5   
 6   <body>
 7      <p>
 8         <script type="text/javascript">
 9            document.write("The date is " + (new Date()).toDateString());
10         </script> 
11      </p>
12   </body> 
13 </html>

When the browser encounters a 3f1c4e4b6b16bbbd69b2ee476dc4f83a tag, as in the above HTML page That way, it's impossible to predict whether JavaScript will add content in the e388a4556c0f65e1904146cc1a846bee tag. Therefore, the browser stops, runs this JavaScript code, and then continues parsing and translating the page. The same thing happens when loading JavaScript using the src attribute. The browser must first download the code for the external file, which takes some time, and then parse and run the code. During this process, page parsing and user interaction are completely blocked.

Because scripts block the downloading process of other page resources, the recommended approach is: place all 3f1c4e4b6b16bbbd69b2ee476dc4f83a tags as close to the bottom of the 6c04bd5ca3fcae76e30b72ad730ca86d tag as possible to minimize the impact of downloading the entire page. Influence. For example:

 1 <html>
 2   <head>
 3     <title>Script Example</title>
 4     <link rel="stylesheet" type="text/css" href="styles.css"> 
 5   </head>
 6   
 7   <body>
 8     <p>Hello world!</p>
 9     <-- Example of recommended script positioning --> 
10       <script type="text/javascript" src="file1.js"></script> 
11       <script type="text/javascript" src="file2.js"></script> 
12       <script type="text/javascript" src="file3.js"></script>
13   </body> 
14 </html>

This code shows the recommended location of the 3f1c4e4b6b16bbbd69b2ee476dc4f83a tag in the HTML file. Although the script downloads block each other, the page has been downloaded and displayed in front of the user, and the speed of entering the page will not appear too slow. This is the Put JS to the bottom mentioned above.

In addition, Yahoo! creates a "union handle" for its "Yahoo! User Interface (Yahoo! User Interface, YUI)" library, which is through their "Content Delivery Network" (Content Delivery Network, CDN)" is implemented. Any website can use a "union handle" URL to indicate which files in the YUI package are included. For example, the following URL contains two files:

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

This URL calls the 2.7.0 version of the yahoo-min.js and event-min.js files. These files are two separate files on the server, but when the server receives this URL request, the two files will be merged together and returned to the client. With this method, there is no need for two 3f1c4e4b6b16bbbd69b2ee476dc4f83a tags (each loading a file), and one 3f1c4e4b6b16bbbd69b2ee476dc4f83a tag can load them. This is the best way to include multiple external Javascripts in an HTML page.

Noblocking Scripts Non-blocking Scripts

The above is the best way to load multiple Javascript scripts in the initial state of the page. Javascript tends to block certain browser processes, such as http requests and interface refreshes, which is the most significant performance problem faced by developers. Keeping JavaScript files short and limiting the number of http requests are just the first steps in creating responsive web applications.

But such as large web pages with a lot of JS code, keeping the source code short is not always the best choice. So, non-blocking scripts came into being. What we need is to gradually add javascript to the page without blocking the browser to some extent.

The key to not blocking the script is to wait until the page has finished loading before loading the Javascript source code, which means starting to download the code after the window's load

event is issued.

Related explanation:

The load event of window will only be triggered once and only once after the page is loaded.

window.

onload=function(){} must wait until all content in the web page is loaded (including all associated files of the element, such as Pictures) before it can be executed , that is, Javascript can access any element in the page at this time.

The following methods are as follows:

Deferred Scripts 延期脚本

Html4为3f1c4e4b6b16bbbd69b2ee476dc4f83a标签定义了一个扩展属性:defer。

这个defer属性指明元素中所包含的脚本不打算修改DOM,因此代码可以稍后执行。defer属性只被Internet Explorer 4+和Firefox 3.5+支持,它不是一个理想的跨浏览器解决方案。在其他浏览器上,defer属性将被忽略。所以,3f1c4e4b6b16bbbd69b2ee476dc4f83a标签会按照正常默认方式处理,即是会造成阻塞。如果得到各个主流浏览器的支持,这仍是一种有效的解决方式。

<script type="text/javascript" src="file1.js" defer></script>

一个带有defer属性的3f1c4e4b6b16bbbd69b2ee476dc4f83a标签可以放置在文档的任何位置,它会在被解析时启动下载,直到DOM加载完成(在onload事件句柄被调用之前)。当一个defer的Javascript文件被下载时,它不会阻塞浏览器的其他处理过程,所以这些文件可以与其他资源一起并行下载。

可以使用下述代码测试浏览器是否支持defer属性:

 1 <html>
 2   <head>
 3     <title>Script Defer Example</title>
 4   </head> 
 5 
 6   <body>
 7     <script defer> alert("defer");</script> 
 8     <script> alert("script"); </script> 
 9     <script> window.onload = function(){ alert("load");}; </script>
10   </body> 
11 </html>

如果浏览器不支持defer,那么弹出的对话框的顺序是“defer”,“script”,“load”。

如果浏览器支持defer,那么弹出的对话框的顺序是“script”,“load”,“defer”。

Dynamic Script Elements 动态脚本元素

DOM允许我们使用Javascript动态创建HTML的几乎所有文档内容,一个新的3f1c4e4b6b16bbbd69b2ee476dc4f83a元素可以非常容易的通过标准DOM创建:

1 var script = document.createElement ("script");
2 script.type = "text/javascript";
3 script.src = "file1.js"; 
4 document.body.appendChild(script);

新的3f1c4e4b6b16bbbd69b2ee476dc4f83a元素加载file1.js源文件。此文件当元素添加到页面后立刻开始下载。此技术的重点在于:无论在何处启动下载,文件的下载和运行都不会阻塞其他页面处理过程。

当文件使用动态脚本节点下载时,返回的代码通常立即执行(除了Firefox和Opera,它们将等待此前的所有动态脚本节点执行完毕)。

大多数情况下,我们希望调用一个函数就可以实现Javascript文件的动态下载。下面的函数封装实现了标准实现和IE实现:

 1  function loadScript(url, callback){
 2     var script = document.createElement ("script") ;
 3    script.type = "text/javascript";
 4      
 5     if (script.readyState){ //IE
 6        script.onreadystatechange = function(){
 7          if (script.readyState == "loaded" || script.readyState == "complete"){
 8            script.onreadystatechange = null;
 9            callback(); 
10           }
11        };
12      } 
13      else { //Others
14        script.onload = function(){ callback();
15      }; 
16    }
17    script.src = url;
18    document.getElementsByTagName("head")[0].appendChild(script); 
19  }
20 
21 loadScript("file1.js", function(){  //调用
22     alert("File is loaded!"); 
23 });

此函数接受两个参数:Javascript文件的Url和一个当Javascript接收完成时触发的回调函数。属性检查用于决定监视哪种事件。最后一步src属性,并将javascript文件添加到head。

动态脚本加载是非阻塞Javascript下载中最常用的模式,因为它可以跨浏览器,而且简单易用。

XMLHttpRequest Script Injection XHR脚本注入

另一个以非阻塞方式获得脚本的方法是使用XMLHttpRequest(XHR)对象将脚本注入到页面中。此技术首先创建一个XHR对象,然后下载Javascript文件,接着用一个动态3f1c4e4b6b16bbbd69b2ee476dc4f83a元素将Javascript代码注入页面。看demo:

 1 var xhr = new XMLHttpRequest(); 
 2 xhr.open("get", "file1.js", true); 
 3 xhr.onreadystatechange = function(){
 4     if (xhr.readyState == 4){
 5       if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304){ // 检查http状态码
 6         var script = document.createElement("script"); 
 7         script.type = "text/javascript";
 8         script.text = xhr.responseText;
 9         document.body.appendChild(script);
10       } 
11    }
12 }; 
13 xhr.send(null);

此代码向服务器发送一个获取file1.js的文件get请求。onreadystatechange事件处理函数检查readyState是不是4,然后检查HTTP状态码是不是有效(200表示确定客户端请求已成功,2xx表示有效回应,304表示一个缓存响应)。如果收到一个有效响应,那么就创建一个新的3f1c4e4b6b16bbbd69b2ee476dc4f83a元素,将它的文本属性设置为从服务器接收到的responseText字符串。这样做实际上会创建一个带有内联代码的3f1c4e4b6b16bbbd69b2ee476dc4f83a元素,一旦新的3f1c4e4b6b16bbbd69b2ee476dc4f83a元素被添加到文档,代码将被执行,并准备使用。

此方法的优点是兼容性佳,且你可以下载不立即执行的Javascript代码。由于代码返回在3f1c4e4b6b16bbbd69b2ee476dc4f83a标签之外,它下载后不会自动执行,这使得你可以推迟执行。

此方法的确定是受到浏览器同源限制,Javascript文件必须与页面放置在同一个域内,不能从CDN(内容分发网络Content Delivery Network)下载。正因为这个原因,大型网页通常不采用XHR脚本注入技术。

Recommended Noblocking Pattern 推荐的非阻塞模式

推荐的向页面加载大量Javascript的方法分为两个步骤:

  • 第一步,包含动态加载Javascript所需的代码,然后加载页面初始化所需的除了Javascript之外的部分。这部分代码尽量小,可能只包含loadScript()函数,它的下载和运行非常迅速,不会对页面造成很大干扰。

  • 第二步,当初始代码准备好之后,用它来加载其余的Javascript。

例如:

1 <script type="text/javascript" src="loader.js">
2 </script> <script type="text/javascript">
3 loadScript("the-rest.js", function(){ 
4   Application.init();
5 }); 
6 
7 </script>

将此代码放置在body的关闭标签36cc49f0c466276486e50c850b7e4956之前。这样做的好处是,首先,这样确保Javascript运行不会影响其他页面的其他部分显示。其次,当第二部分Javascript文件完成下载,所有应用程序所必须的DOM已经创建完毕,并做好被访问的准备,避免使用额外的事件处理(如window.onload)来得知页面是否已经准备好了。

另一个选择是直接将loadScript()函数嵌入在页面中,这可以减少一个http请求的开销。例如:

 1 <script type="text/javascript"> 
 2   function loadScript(url, callback){
 3     var script = document.createElement ("script");
 4    script.type = "text/javascript";
 5    
 6     if (script.readyState){ //IE script.onreadystatechange = function(){
 7       if (script.readyState == "loaded" || script.readyState == "complete"){
 8         script.onreadystatechange = null; 
 9         callback();
10       } 
11     };
12   } else { //Others 
13    script.onload = function(){
14      callback(); 
15    };
16   }
17   script.src = url; 
18   document.getElementsByTagName("head")[0].appendChild(script);
19 }
20 
21 loadScript("the-rest.js", function(){
22   Application.init(); 
23 });
24 </script>

一旦页面初始化代码下载完成,还可以使用loadScript()函数加载页面所需的额外功能函数。

介绍一个通用的工具,Yahoo! Search的Ryan Grove创建了LazyLoad库。LazyLoad是一个强大的loadScript()函数。LazyLoad精缩之后只有大约1.5KB。用法举例如下:

1 <script type="text/javascript" src="lazyload-min.js"></script> 
2 <script type="text/javascript">
3   LazyLoad.js("the-rest.js", function(){ 
4     Application.init();
5   }); 
6 </script>

Summary 总结

  • 将所有3f1c4e4b6b16bbbd69b2ee476dc4f83a标签放置在页面底部,紧靠关闭标签36cc49f0c466276486e50c850b7e4956的上方。此方法可以保证页面在脚本运行之前完成解析。

  • 将脚本成组打包。页面的3f1c4e4b6b16bbbd69b2ee476dc4f83a标签越少,页面的加载速度就越快,响应也更迅速。不论外部脚本文件还是内联代码都是如此。

  • 有几种方法可以使用非阻塞方式下载Javascript:

    • 为3f1c4e4b6b16bbbd69b2ee476dc4f83a标签添加defer属性

    • 动态创建3f1c4e4b6b16bbbd69b2ee476dc4f83a元素,用它下载并执行代码

    • 用XHR对象下载代码,并注入到页面

通过上述策略,可以极大提高那些使用Javascript代码的网友应用的实际性能。

The above is the detailed content of Sample code sharing for JavaScript non-blocking loading performance optimization. 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