Home  >  Article  >  Web Front-end  >  Detailed explanation and summary of several knowledge points to improve JavaScript performance

Detailed explanation and summary of several knowledge points to improve JavaScript performance

黄舟
黄舟Original
2017-03-09 14:58:591339browse

Detailed explanation of several knowledge points to improve JavaScript performance:

I spent some time reading most of the book "High Performance JavaScript" some time ago Books, and then started working on projects. I am glad that the busiest week has passed. Due to lack of time, I didn't write many study notes this month. After the most arduous week, I stayed up late and read the book these two nights... I finally shut down this book when I was still alive...

Now that I have finished reading, I have to learn something. Let me talk about my views on this book first. Overall, the content is good, but it feels a bit old (as a front-end novice, it may be that my own level is limited and I fail to understand the true meaning). In the process of reading this book, I also wrote a lot of code for testing. I also conducted breakpoint tracking on the execution of the writing method advocated in this book and the original popular writing method, so as to understand the problems that can be actually measured. Of course, If you can't see it even if you set a breakpoint and follow the execution, there's nothing you can do about it. Regarding the knowledge points in the book, here is just a brief summary of some of the knowledge points that I personally recommend. Of course~ don’t criticize if you don’t like it.

##For the loading position of js files

In HTML files, the 3f1c4e4b6b16bbbd69b2ee476dc4f83a tag can be added to the 93f0f5c25f18dab9d176bd4f6de5d30e area and e085cb568f5e82ca30da9309f8ea24b4 tag (that is, behind the content presented on all pages), and the css file in the 93f0f5c25f18dab9d176bd4f6de5d30e area (no one wants to see it) A page with a cluttered layout). Doing this will allow users to see a layout page instead of a blank page. Then some people will point out: The data must be loaded through js requests. What should I do? The loading of data can be sorted. Interfaces that are urgently needed can be executed first. Those that are not so needed can be deferred and a simple loading animation or prompt can be made at the same time.

2. If these js files specify that they need to be executed first to better display the page content, then put a small loading animation on the first js or page. , you can have some interesting or cute animated scenes. This can also better avoid the boredom of waiting for users. Maybe they will be more interested in the loading animation, which can improve the user experience of the project.

Final recommendation: Place the 3f1c4e4b6b16bbbd69b2ee476dc4f83a tag as much as possible in front of the 36cc49f0c466276486e50c850b7e4956 tag to improve user experience.

For the merging of js files

In many team developments, we may place code blocks with different functions in different js files to facilitate the cooperation of everyone in writing code during the development process. It will be more convenient, after all, you only need to find the corresponding folder or file instead of finding a method in a long file. This will indeed improve team development efficiency and make it easier for new people to perform secondary development and maintenance after joining. So how about putting this issue into page performance? This is exactly the problem, as stated in the book: Each HTTP request brings with it additional performance overhead, so downloading one single 100 KB file will be faster than downloading four 25 KB files.

Downloading 1 100KB file is faster than downloading four 25KB files, and it is of great benefit to distinguish each file during the development process, so the problem of merging will be dealt with after the development is completed. I believe this operation will be familiar to everyone. Well, there are so many front-end tools now, just use whatever compression you are used to~

Here is a brief mention, you can also use the defer and async attributes when loading files, for delayed loading and asynchronous loading. In modern browsers, most of them already support the defer attribute. I am not used to using it yet, and I don’t know if there will be any specific problems. Friends who are interested can google this knowledge point by themselves, and I will briefly mention it here.

Most of today’s frameworks also support lazy loading and on-demand loading.

Faster data access

For the browser, the deeper an identifier is located, the slower it is to read and write it (for this point, the prototype chain This is also true). This should not be difficult to understand. A simple analogy is: the farther the grocery store is from your home, the longer it takes you to make soy sauce... Naughty kid, if you take so long to make soy sauce, the vegetables will be burnt -.-~

If we need to use a variable value multiple times within the current function, then we can use a local variable to store it first. The case is as follows:

  //修改前
  function showLi(){
      var i = 0;
      for(;i<document.getElementsByTagName("li").length;i++){    //一次访问document
          console.log(i,document.getElementsByTagName("li")[i]);  //三次访问document
      };
  };
  //修改后
  function showLi(){
      var li_s = document.getElementsByTagName("li");  //一次访问document
      var i = 0;
      for(;i<li_s.length;i++){
          console.log(i,li_s[i]);  //三次访问局部变量li_s
      };
  };

Optimization of DOM operations

As we all know, DOM operations consume far more performance than JavaScript execution. Although we cannot avoid operating DOM, we can try to reduce the performance consumption of this operation.

Let us explain this problem through code:

  function innerLi_s(){
      var i = 0;
      for(;i<20;i++){
          document.getElementById("Num").innerHTML="A"; //进行了20次循环,每次又有2次DOM元素访问:一次读取innerHTML的值,一次写入值
      };
  };

A rewrite of the above method:

  function innerLi_s(){
      var content ="";
      var i = 0;
      for(;i<20;i++){
          content += "A";  //这里只对js的变量循环了20次
      };
      document.getElementById("Num").innerHTML += content;  //这里值进行了一次DOM操作,又分2次DOM访问:一次读取innerHTML的值,一次写入值
  };

Reduce the redrawing and reflowing of Dom

Changes in element layout or content additions, deletions, or browser window size changes will cause reflowing, and the font color or background color will Modifications will cause redrawing.
For operations similar to the following code, it is said that most modern browsers have been optimized (optimized into 1 rearrangement version):

  //修改前
  var el = document.getElementById("p");
  el.style.borderLeft = "1px"; //1次重排版
  el.style.borderRight = "2px"; //又1次重排版
  el.style.padding = "5px"; //还有1次重排版
  //修改后
  var el = document.getElementById("p");
  el.style.cssText = "border-left:1px;border-right:2px;padding:5px"; //1次重排版

For multiple Operation, the following three methods can also reduce the number of rearrangements and redraws:

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

2.document.createDocumentFragment() creates a document fragment for processing, and appends it to the page for 1 rearrangement after the operation

3.var newDOM = oldDOM.cloneNode(true) creates a Dom copy, and after modifying the copy, oldDOM.parentNode.replaceChild (newDOM, oldDOM) covering the original DOM 2 rearrangements

Optimization of loop

This should be a writing method that more people know, just go through it simply (still use code + later) Comment form description)~

  //修改前
  var i = 0;
  for(;i<arr.lengthli++){  //每次循环都需要获取数组arr的length
      console.log(arr[i]);
  }
  //修改后
  var i = 0;
  var len = arr.length;  //获取一次数组arr的length 
  for(;i<len;i++){
      console.log(arr[i]);
  }
  //or
  var i = arr.length;;
  for(;i;i--){
      console.log(arr[i]);
  }

Reasonable use of binary

For example: take modulo 2, then the lowest bit of even numbers is 0, and the lowest bit of odd numbers is 0, the result of the bitwise AND operation with 1 is 0, the lowest bit of the odd number is 1, the result of the bitwise AND operation with 1 is 1.

The code is as follows:

  .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";
      }
  };

Although modern browsers have done a good job, I feel that this is my pursuit of code quality. And maybe not paying attention to one or two points will not have much impact on performance, but after optimizing from multiple points, what may happen will be a qualitative leap~

The above is the detailed content of Detailed explanation and summary of several knowledge points to improve JavaScript performance. 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