English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Summary of several performance improvement points in JavaScript (recommended)

Recently, I spent some time reading most of the book 'High Performance JavaScript', and then I got busy with the project. I'm glad that the busiest week is over. Due to the lack of time, I didn't write many study notes this month. After the most exhausting week, I've been reading under the lamp at night these two days... Finally, I finished reading the book in a state of being 'bleeding'.

Since it's over, I guess I've learned something. Let's talk about my opinion of this book first. Overall, the content is still good, but I feel it's a bit outdated (as a front-end beginner, it may also be due to my limited level, unable to understand the true meaning). During the process of reading this book, I also wrote a lot of code for testing, and I tracked breakpoints for the execution of the writing style advocated by this book and the general writing style, understanding the problems that can be tested in actual situations, of course, it's also impossible to see by following the execution of breakpoints. For the knowledge points in the book, I just simply organize a part that I personally advocate, of course~ Don't be angry if you don't like it.

Regarding the loading position of JavaScript files

In the HTML file, the <script> tag can be placed in the <head> area or the <body> area. Due to the single-threaded nature of JavaScript execution and UI rendering, if the JavaScript file is loaded, it may block the parsing process of the page later, causing the page to wait until the JavaScript file is completely loaded and executed before continuing with the next operation. This may lead to the page being blank or unresponsive. As a front-end developer, it's not just about meeting the requirements, but also about providing a high-quality user experience. Therefore, we need to eliminate the user's boring waiting time and offer two solutions to this problem:

1If there are no special requirements indicating that the JavaScript file needs to be loaded and compiled before the page rendering, then choose to place the JavaScript file in the </Before the body>tags (that is, the content displayed on all pages), the CSS file should still be placed in the <head> area (nobody wants to see a page with a chaotic layout). This way, the user can see a page with a layout first rather than a blank page. Some people might point out: But the data needs to be loaded in through JavaScript, what should we do? We can sort the loading of the data, executing the interfaces that need to be displayed urgently first, and those that are not so urgent can be executed later, while also making a simple loading animation or prompt.

2If these js files specify that they need to be executed first in order to better display the page content, then put a loading animation at the first js or at the beginning of the page. You can put some interesting or cute animation scenes. This can also better avoid the boring waiting of users, and maybe people are even more interested in this loading animation, which can improve the user experience of the project.

Finally, it is recommended to place the <script> tag as close as possible to the </to load before the body> tag to enhance user experience.

For merging js files

In many team developments, we may place different functional code blocks in different js files, so that it is more convenient for everyone to cooperate in writing code during the development process. After all, it is only necessary to find the corresponding folder or file rather than searching for a method in a very long file. This indeed improves the efficiency of team development and makes it easier for new people to carry out secondary development and maintenance. So, what about this issue in terms of page performance? This is exactly the problem. As mentioned in this book: Each HTTP request brings additional performance overhead, so downloading one single 10A 0 KB file will be faster than downloading four 25 KB files.

Download1A100KB file is faster than downloading4A25KB files need to be fast, and it is very beneficial to distinguish between different files during the development process. So, this merging issue can be handled after the development is completed. I believe everyone is not unfamiliar with this operation. Now, with so many front-end tools, everyone can use the compression they are accustomed to.

Here, I simply mention that the defer and async attributes can be used for loading files, which are used for deferred loading and asynchronous loading. Most modern browsers already support the defer attribute. I'm not used to using it and don't know if there will be any specific problems. Those who are interested can google this knowledge point, and I'll just briefly mention it here.

Nowadays, most frameworks also work with lazy loading and on-demand loading.

Faster data access

For a browser, the deeper a identifier is located, the slower the speed of reading and writing it becomes (this is also true for the prototype chain). This should be easy to understand; a simple analogy would be: the farther the grocery store is from your home, the longer it takes you to buy soy sauce... Dear child, taking so long to buy soy sauce, the vegetables would have been burned to a crisp already. -.-~~

If we need to use a variable value multiple times within the current function, we can store it in a local variable first, for example:

//Before modification
 function showLi(){
   var i = 0;
   for(; i<document.getElementsByTagName("li").length; i++{  //one access to document
     console.log(i,document.getElementsByTagName("li")[i]); //three accesses to document
   };
 };
 //After modification
 function showLi(){
   var li_s = document.getElementsByTagName("li"); //one access to document
   var i = 0;
   for(; i<li_s.length; i++{
     console.log(i,li_s[i]); //three accesses to the local variable li_s
   };
 };

Optimization of DOM operations

As is well known, DOM operations are much more performance-intensive than JavaScript execution, although we cannot avoid DOM operations, we can try to minimize the performance impact of these operations.

Let us explain this issue through code:

function innerLi_s(){
   var i = 0;
   for(; i<20; i++{
     document.getElementById("Num").innerHTML="A"; //was performed20 loops, each with2times of DOM element access: one read of the innerHTML value, one write of the value
   };
 };

Rewrite the above method once:

function innerLi_s(){
   var content ="";
   var i = 0;
   for(; i<20; i++{
     content += "A"; //Here, only the js variable was cycled20 times
   };
   document.getElementById("Num").innerHTML += content; //Here, a DOM operation was performed, and it was divided2times of DOM access: one read of the innerHTML value, one write of the value
 };

Reduce DOM repaint and reflow

Changes in element layout or content additions, deletions, and modifications, or changes in the browser window size will cause a reflow, while changes in font color or background color will cause a repaint.

It is said that modern browsers have optimized operations similar to the following code (optimizing them into1reformatting):

//Before modification
 var el = document.getElementById("div");
 el.style.borderLeft = ""1px"; //1repositioning
 el.style.borderRight = ""2px"; //Again1repositioning
 el.style.padding = ""5px"; //There is1repositioning
 //After modification
 var el = document.getElementById("div");
 el.style.cssText = "border"-left:1px;border-right:2px;padding:5px"; //1repositioning

For multiple operations, the following three methods can also reduce the number of reflows and repaints:

1.Dom first hidden, then displayed after the operation 2repositioning (temporary display:none)

2.document.createDocumentFragment() create a document fragment to handle, append to the page after the operation 1repositioning

3.var newDOM = oldDOM.cloneNode(true) create a Dom copy, modify the copy after oldDOM.parentNode.replaceChild(newDOM,oldDOM) cover the original DOM 2repositioning

Optimization of the loop

This is a writing method that most people know, so let's just go through it (the code is still used later)+(Comment form)~

//Before modification
 var i = 0;
 for(;i<arr.lengthli++{ //The length of the array arr needs to be obtained in each loop
   console.log(arr[i]);
 }
 //After modification
 var i = 0;
 var len = arr.length; //Get the length of the array arr once 
 for(;i<len;i++{
   console.log(arr[i]);
 }
 //or
 var i = arr.length;;
 for(;i;i--{
   console.log(arr[i]);
 }
.odd{color:red}
.even{color:yellow}
<ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
    <li>6</li>
</ul>
var i = 0;
 var lis = document.getElementsByTagName("li");
 var len = lis.length;
 for(;i<len;i++{
   if(i&1{
     lis[i].className = "even";
   }
     lis[i].className = "odd";
   }
 };

This article summarizes several points to improve the performance of JavaScript (recommended) is all the content shared by the editor, hoping to provide a reference for everyone, and also hope that everyone will support and cheer for the tutorial.

You May Also Like