Home > Article > Web Front-end > Summary of JavaScript knowledge points: how to improve performance_javascript skills
The performance issues of JavaScript cannot be underestimated, which requires us developers to pay more attention to some details when writing JavaScript programs. This article introduces the knowledge points of JavaScript performance optimization in great detail, which is definitely useful information.
Let me first consolidate the basic syntax of javascript:
Basic syntax of javascript
Use the var keyword to define variables
Syntax: var variable name=variable value
identifier: ①, composed of letters, numbers and underscores. It cannot start with a number. It cannot be a keyword. It is strictly case-sensitive
Data type:
Numeric type: number
String: string
Boolean type: boolean
Special data types: undefined empty undefined unassigned
Null value: null
Reference type object function
Detect the data type of the parameter: typeof() returns the string corresponding to the data type
Usage of two equal signs == and three equal signs ===
==: Comparison values are equal regardless of data type
===: Congruent comparison is related to both numerical values and data types
Boolean environment: automatically convert to Boolean value when encountering if
Boolean environment in string string: empty is false, non-empty is true
Boolean environment in numerical number: 0 is false, non-0 is true
The relationship between number and string
①. When encountering, perform splicing operation
②. When operations need to be performed, the string must be converted into a numerical value
Conversion method 1, string*1 into numeric type
Conversion method 2: Convert Number (string) to numeric type
1: Loading location of js files
In HTML files, 3f1c4e4b6b16bbbd69b2ee476dc4f83a tags can be added to the 93f0f5c25f18dab9d176bd4f6de5d30e area and 6c04bd5ca3fcae76e30b72ad730ca86d area. In view of the single-threaded reason for JavaScript execution and UI rendering, if the js file is loaded, it will block the subsequent parsing process of the page. The page will wait until the js file is fully loaded and run before continuing to perform the operation. Then the problem arises, the page may be blank or stuck. As a front-end developer, it is important not only to realize the requirements, but also to provide a high-quality user experience. Then we need to eliminate the boring waiting of users. To solve this problem, here are two solutions that I have 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, then choose to place the js file before the 36cc49f0c466276486e50c850b7e4956 tag (that is, after all the content presented on the page). The css file is still placed in the 93f0f5c25f18dab9d176bd4f6de5d30e area (no one wants to see a page with a messy 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, which can be something 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.
2: Merging js files
In many team developments, we may place code blocks with different functions in different js files, so that it is more convenient for everyone to collaborate on writing code during the development process. After all, we only need to find the corresponding folder or file. Not looking for 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, 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 one 100KB file is faster than downloading four 25KB files, and there are great benefits in distinguishing each file during the development process, so the issue of merging will be dealt with after the development is completed. I believe This operation will be familiar to everyone, right? There are so many front-end tools now, so just use whatever compression you are used to~
I would like to briefly mention here that the defer and async attributes can also be used when loading files for lazy loading and asynchronous loading. In modern browsers, most of them already support the defer attribute. I am not used to using this yet. Well, 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.
Three: Faster data access
For the browser, the deeper the location of an identifier, the slower it will be to read and write it (the same is true for the prototype chain). This should not be difficult to understand. A simple metaphor 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 }; };
Four: Optimization of DOM operations
As we all know, DOM operations consume far more performance than JavaScript execution. Although we cannot avoid operating on DOM, we can try to reduce the performance consumption of this operation as much as possible.
Let’s explain this through code:
function innerLi_s(){ var i = 0; for(;i<20;i++){ document.getElementById("Num").innerHTML="A"; //进行了20次循环,每次又有2次DOM元素访问:一次读取innerHTML的值,一次写入值 }; };
Rewrite 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的值,一次写入值 };
5: Reduce Dom redrawing and rearrangement
Changes in element layout, content additions, deletions, or browser window size changes will result in reflow, while changes in font color or background color will result in redrawing.
For operations similar to the following code, it is said that most modern browsers have been optimized (optimized into 1 rearranged version):
//修改前 var el = document.getElementById("div"); el.style.borderLeft = "1px"; //1次重排版 el.style.borderRight = "2px"; //又1次重排版 el.style.padding = "5px"; //还有1次重排版 //修改后 var el = document.getElementById("div"); el.style.cssText = "border-left:1px;border-right:2px;padding:5px"; //1次重排版
For multiple operations, the following three methods can also reduce the number of reflows and redraws:
1.Dom is hidden first, then displayed after operation. 2 rearrangements (temporary display:none)
2.document.createDocumentFragment() creates document fragment processing, appends to the page after operation, and rearranges once
3.var newDOM = oldDOM.cloneNode(true) creates a copy of Dom. After modifying the copy, oldDOM.parentNode.replaceChild(newDOM,oldDOM) overwrites the original DOM and rearranges it 2 times
5: Loop optimization
This should be a writing method that many people know. You can simply go through it (it will still be explained in the form of code comments later)~
//修改前 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]); }
6: Proper use of binary
For example: taking modulo 2, the lowest bit of even numbers is 0, the lowest bit of odd numbers is 0, the result of bitwise AND operation with 1 is 0, the lowest bit of odd number is 1, the result of 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, the possible results will be a qualitative leap~