In the process of daily work and project, we sometimes encounter the situation that the page loading takes a long time to load out, which seriously affects the user experience effect. While sometimes it may be due to network issues, other times it’s due to the front-end code not being optimized enough. Therefore, after consulting relevant materials and practicing, the following knowledge points are summarized to improve performance. If there is anything wrong in writing, I hope all the gods will point it out and give directions.
- The data access
- Dom
- cycle
1. Data access
1. Place all script tags as close as possible to the bottom of the body tag to minimize the impact on the page download.
2. Use global variables as little as possible (solution: use strict mode to avoid this). Because the deeper the variable is in the scope chain, the longer the access time is. Local variables are in the first object in the scope chain, and global variables are always at the end of the scope chain, so global variables are always the slowest. 3, avoid global query, if you must use a global variable, and you need to use the global variable multiple times in a function, you can define a local variable to point to the global variable, to shorten the depth of the query in the scope chain.
function addTotrackData(){ var allChildrenNode=getAllChildrenDepartmentNodes(); for (var i = 0; i < allChildrenNode.length; i++) { for (var j=0,len=track.length; j<len; j++) { if (trackNode[j]["userId"] == allChildrenNode[i]) { trackNode[j]["isOnMap"] = true; }}}}Copy the code
The above code can be rewritten as shown below
function addTotrackData(){ var allChildrenNode=getAllChildrenDepartmentNodes(); var track=trackNode; for (var i = 0; i < allChildrenNode.length; i++) { for (var j=0,len=track.length; j<len; j++) { if (track[j]["userId"] == allChildrenNode[i]) { track[j]["isOnMap"] = true; }}}}Copy the code
4. Store the length attribute of the set as a local variable and use this variable in the iteration.
for (var j=0,len=track.length; j<len; j++)Copy the code
4. Avoid using the with expression because it increases the length of the scope chain (with can treat an object with no or more properties in a completely separate lexical scope, and var declarations are added to the scope of the function defined within the with block). With is often used as a shortcut to repeat references to multiple properties of the same object without having to repeat references to the object itself. The catch clause of a try-catch should be treated with care; it has the same effect. Var obj={a:1, b:2, c:3} with(obj){a=2; b=3; c=4 }
Function foo(obj){with(obj){a=2; } } var obj1={ a:1 } var obj2={ b:3 } foo(obj1); console.log(obj1.a); //2 foo(obj2); console.log(obj.a); //undefined console.log(a); //2 A is leaked to the global scope. With only modifs the object properties passed in, not adds new properties to the object.Copy the code
5. The deeper a property or method is in the prototype chain, the slower it is accessible. 6. When declaring variables, multiple variables can be merged to reduce memory consumption.
var a; var b; var c; Var a,b,cCopy the code
7. Do not use eval(which parses the corresponding string into javascript code and runs it). It is unsafe, performance intensive (twice, once parsed into a JS statement, once executed), and changes the lexical scope of eval().
function foo(str,a){ aval(str); Log (a,b)} var b=2; foo("var b=3",1);Copy the code
8, the use of image lights to achieve fast transmission of data to the server. Format :(new Image).src=url? Params. Join (” & “). 9. Creating objects and arrays using arrays and objects’ direct quantities is faster than creating and initializing them in indirect quantities.
var obj={};
var arr=[];
Copy the code
10. Try to use the native methods that come with javascript, such as math.abs (). 11. Do not repeat the same operation. Use lazy loading and conditional preloading (? The code for lazy loading is as follows:
function addhandler(target,eventType,handler){ if(target.addEventListener){ addhandler=function(){ target.addEventListener(eventType,handler,false); }; }else{ addhandler=function(){ target.addEventListener("on"+eventType,handler) }; } addhandler(target,eventType,handler); } var dom=document.getElementById("test"); Addhandler (dom,"click",function(){console.log(" test "); })Copy the code
Reduce the number of Ajax requests. On the server side, set the HTTP header to ensure that the returned packet is cached in the browser (the Expires header tells the browser how long it should cache the returned packet, and its value is a date. Any request made after this date will fetch data from the server. The caching problem can be solved by attaching a timestamp to the file name as well.
Format: Expires: Mon, 28 Jul 2014 23:30:00 GM).Copy the code
13. Use a content delivery network (CDN) to provide javascript files for improved performance while managing compression and caching.
2. Dom operations
Dom (Document Object Model) is a language-independent application interface that works with XML and HTML documents. The interface in the browser is implemented in javascript. Dom and javascript are seen as two islands, connected by a toll bridge. The general advice is to stay on javascript island.
Use innerHTML instead of DOM operations to reduce DOM operations and optimize javascript performance.
Var STR ="" var dom= document.getelementById ("test"); var start1=new Date(); for(var j=0; j<100000; j++){ var div=document.createElement("div"); div.innerText="test"; dom.append(div); } var end1=new Date(); The console. The log (" dom way: "+ (end1 - start1)); Var content=""; var start=new Date(); for(var i=0; i<10000; i++){ content=content+"<div>test</div>"; } document.getElementById("test").innerHTML=content; var end=new Date(); The console. The log (" innerHTML way: "+ (end - start)); / / innerHTML way: 35Copy the code
2. If a Dom element or collection is accessed more than once, it is best to use a local variable to cache the Dom member. Using local variables to cache collection references and collection elements in a loop will speed things up. 3. Traversal of children is faster than childNodes. Children does not distinguish between (including) comment nodes and empty text nodes, so it is faster. 4. Use element.clonenode (bool) to replicate a node. If bool is false, only the current node is replicated. This is faster than document.createElement(). 5, the use of the document. QuerySelector and document. QuerySelectorAll (” div. Warning, div. Notice “) to quickly find. Because they return a NodeList — an array-like object made up of qualified nodes, rather than an HTML collection (which always shows existence), they avoid the inherent performance problems (as well as the existing logic problems). QuerySelectorAll (“div.warning,div.notice”) also allows federated queries. 6. When changing styles, you can use div. Style.
var el = document.getElementById('mydiv'); Dom el.style. BorderLeft = '1px'; el.style.borderRight = '2px'; El. Style. Padding = '5 px; Dom el.style.cssText = 'border-left: 1px; border-right: 2px; padding: 5px; 'Copy the code
7. Try to avoid writing Style attributes in HTML tags. Use external styles for easy maintenance and modification. 8. Avoid empty Src for images, iFrame, etc. Empty Src reloads the current page, affecting speed and efficiency. 9. Use event delegation. Element join event handles can affect page performance, and delegating reduces element join events by taking advantage of event bubbling performance. (Event hooking occurs in onLoad or DOMContentReady) events. 10, avoid CSS expressions, avoid advanced selectors (such as offspring, pseudo-class selectors), wildcard selectors. 11, compressed files (GZIP), can reduce memory usage, while reducing the query time. Merge styles and scripts and use CSS sprites (Sprite charts) (this is to reduce the number of requests to the server and thus optimize performance). Shorten page loading time by displaying the structure of the page first and then using Ajax to get the rest of the important files.
3, cycle
1. For-in is the slowest of the four loop methods and is typically used to loop through objects (to find out whether they are self properties or prototype properties). Looping through arrays is not recommended. Unless you are iterating over an object whose properties are unknown, for-in is generally not used. 2. Change the order of cycle conditions to improve cycle performance.
For (var I =items.length; i--;) {//todo} for(var I =0,len= item.length; i<len; i++){ //todo }Copy the code
3. Optimize performance by reducing the volume of cycles.