JavaScript summarizes several knowledge points for improving performance of recommendations

  • 2021-07-22 08:34:40
  • OfStack

Some time ago, I spent time reading most of the book High Performance JavaScript, and then I started to be busy with the project. Fortunately, the busiest week has passed. Because I can't spare time, I don't write many study notes this month. After the most bitter week of X, I can be regarded as burning the midnight oil in these two nights... Finally, I put this book shut down at the time of residual blood...

Now that I have finished reading it, I have to learn something. Let's talk about our views on this book first. On the whole, the content is good, but I feel a little old (as a front-end white, I may have limited level and failed to realize the true meaning). In the process of reading this book, I also wrote a lot of code to test, and tracked the breakpoints of the writing method advocated in this book and the execution of the original popular writing method, and understood the problems that can be actually measured. Of course, there is no way to follow the execution of the lower breakpoints. For the knowledge points in the book, here is just a simple collation of one part of personal esteem, of course ~ don't spray if you don't like it.

Load location for js file

In the HTML file, < script > Labels can be added to the < head > Regional and < body > Regional. Here, due to the single thread of JavaScript execution and UI rendering, if the loading of js file blocks the parsing process of the page later, the page will wait until the js file is fully loaded and running before continuing to perform the operation. Then the problem comes, which may lead to page blank or jamming. As a front-end developer, it is important not only to realize the requirements, but also to have a high-quality user experience. Then we need to eliminate the boring waiting of users. To solve this problem, here are two solutions that Ben Beast thought of:

1. If the js file has no special requirements indicating that it needs to be loaded and compiled before the page is rendered, choose to put the js file in < /body > Tag (that is, after the rendered content of all pages), css file is still placed in < head > Area (no one wants to see a page with disorganized layout). In this way, the user can see the layout page instead of the blank page first, so some people will point out that the data has to be loaded through js request. What should I do? You can sort the loading of data, put the interface that needs to be presented in front of the execution, and delay the execution if you don't need it. At the same time, you can do a simple loading animation or prompt.

2. If these js files indicate that they need to be executed first in order to better display the page content, then put a small loading animation on the first js or page, which can create some interesting or MengMeng animation scenes. This is also a better way to avoid the boredom of users waiting. Maybe people are more interested in this loading animation, which can enhance the user experience of the project.

Final recommendation: Will < script > Put the labels as far as possible < /body > Tag to enhance the user experience.

Merge for js files

In many team development, we may put code blocks with different functions in different js files, so that it will be more convenient for everyone to write code together in the development process. After all, we only need to find the corresponding folder or file instead of finding a method in a long file. This will really improve the efficiency of team development and make it easier to develop and maintain twice after new people join. So what about putting this problem in page performance? This is the problem, which is pointed out in this book: Each HTTP request brings with additional performance overhead, so downloading one single 100 KB file will be faster than KB files.

Download 1 100KB file than download 4 25KB file to be faster, and the development process to distinguish each file has great benefits, then merge this problem on the development after processing, I believe this operation everyone will not be unfamiliar with it, now the front-end tools are so rich, you are used to what compression with what compress it ~

It is simply mentioned here that defer and async attributes can also be used in loading files for delayed loading and asynchronous loading. In modern browsers, most of them already support defer attributes, and they are not used to using this amount, and they don't know if there will be any problems. Interested friends can google this knowledge point by themselves. Here is a simple mention.

Most of the current frameworks also cooperate with lazy loading and on-demand loading.

Faster data access

For browsers, the deeper an identifier is located, the slower it is to read and write it (for this, the same is true of prototype chains). This should not be difficult to understand. The simple metaphor is: the farther away the grocery store is from your home, the longer it takes you to make soy sauce... Xiong Haizi, after making soy sauce for so long, the food will burn early---~

If we need to use a variable value multiple times in the current function, we can store it with a local variable first, as follows:


// Before modification 
 function showLi(){
   var i = 0;
   for(;i<document.getElementsByTagName("li").length;i++){  //1 Second visit document
     console.log(i,document.getElementsByTagName("li")[i]); //3 Second visit document
   };
 };
 // After modification 
 function showLi(){
   var li_s = document.getElementsByTagName("li"); //1 Second visit document
   var i = 0;
   for(;i<li_s.length;i++){
     console.log(i,li_s[i]); //3 Secondary access to local variables li_s
   };
 };

Optimization of DOM Operation

As we all know, DOM operation consumes much more performance than javascript. Although we can't avoid operating DOM, we can try our best to reduce the performance consumption of this operation.

Let's explain this problem through code:


function innerLi_s(){
   var i = 0;
   for(;i<20;i++){
     document.getElementById("Num").innerHTML="A"; // Has been carried out 20 Secondary loop, every time there is 2 Times DOM Element access: 1 Secondary read innerHTML The value of, 1 Secondary write value 
   };
 };

Rewrite the above method once:


function innerLi_s(){
   var content ="";
   var i = 0;
   for(;i<20;i++){
     content += "A"; // It's only right here js The variable of loops 20 Times 
   };
   document.getElementById("Num").innerHTML += content; // Here the value is carried out 1 Times DOM Operation, and points 2 Times DOM Visits: 1 Secondary read innerHTML The value of, 1 Secondary write value 
 };

Reduce redrawing and retypesetting of Dom

Element layout changes, content additions and deletions, or browser window sizes will result in rearrangement, while font or background color changes will result in redrawing.

For operations similar to the following code, it is said that most modern browsers have been optimized (optimized to one relayout):


// Before modification 
 var el = document.getElementById("div");
 el.style.borderLeft = "1px"; //1 Sub-retypesetting 
 el.style.borderRight = "2px"; // Again 1 Sub-retypesetting 
 el.style.padding = "5px"; // And 1 Sub-retypesetting 
 // After modification 
 var el = document.getElementById("div");
 el.style.cssText = "border-left:1px;border-right:2px;padding:5px"; //1 Sub-retypesetting 

For multiple operations, the following three methods can also reduce the number of retypesetting and redrawing:

1. Dom is hidden first, and then rearranged twice after operation (temporary display: none)

2. document. createDocumentFragment () Creates document fragment processing and appends it to the page for rearrangement once after operation

3. var newDOM = oldDOM. cloneNode (true) Create a copy of Dom. After modifying the copy, oldDOM. parentNode. replaceChild (newDOM, oldDOM) overwrite the original DOM for 2 rearrangements

Optimization of cycle

This should be a writing method known to more people, and it can be simply taken (explained in the form of code + comments later) ~


// Before modification 
 var i = 0;
 for(;i<arr.lengthli++){ // Each loop needs to get an array arr Adj. length
   console.log(arr[i]);
 }
 // After modification 
 var i = 0;
 var len = arr.length; // Get 1 Number group arr Adj. length 
 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";
   } else{
     lis[i].className = "odd";
   }
 };

Related articles: