Front-end Engineering Optimization: javascript optimization Summary

Source: Internet
Author: User

Front-end Engineering Optimization: javascript optimization Summary
I think optimizing javascript is a profound learning. Here, I can only stand on the shoulders of my predecessors. I want to give a simple understanding of it, but I also hope to give it a drill. If there is something wrong with it, please confirm. First of all, we must realize that the key to optimizing js is to optimize its running speed and use this as the starting point. The javascript optimization principle is: the principle satisfies the consideration of the majority of cases. In extreme cases, the ability should take both measures into consideration. The reason is that, one of the most important factors that affect the user experience is the response time of 0.1 s: the user feels very smooth 1.0 s: the user's operations may be occasionally affected, and the user can already feel a bit unsmooth 10 s: the impact on users is serious, and corresponding progress prompts are required. Users will also be somewhat frustrated (// I think 10 s is too broad, usually more than 2 S can't stand it). Of course, js optimization is only one of the many aspects that need to be improved to improve the response time, the depth of front-end optimization knowledge, only in-depth understanding, will be surprised that the front-end needs to grasp the knowledge is so much, of course, invisible will also put pressure on people | motivation. I am far away, but I still want to recommend two blogs about front-end optimization: a step-by-step Summary of front-end engineering opening Speed Optimization and the best web Front-end optimization practices and tools. Continue with the question. OK. Now you know that the goal is to increase the response time and speed up the operation. What feasible solutions are there: management scope operation data flow control Reflow DOM operation long run script processing management scope to give a chestnut: <span style = "font-size: 16px;"> var foo = 1; function test () {// perform a series of operations on the variable foo} function test2 () {var foo = 1; // perform a series of operations on the variable foo} </span> that is, local variables exist in active objects. The parser only needs to find a single object in the scope. In JavaScript, we should try our best to replace global variables with local variables. Everyone knows this sentence, but who said it first? Why? What is the basis? If this is not done, how much will the performance suffer? The following is an excerpt from JavaScript Variable Performance: The most common advice on how to improve JavaScript Performance is to use local variables as much as possible) to replace global variables ). During my nine years in Web development, this suggestion has always been in my ears and never been questioned. The basis of this suggestion comes from the JavaScript processing scope (scoping) and identifier resolution. First, we need to make it clear that a function is embodied in JavaScript as an object. The process of creating a function is actually the process of creating an object. Each function object has an internal attribute called [Scope], which contains the Scope information during function creation. In fact, the [[Scope] attribute corresponds to a Variable Objects list. Objects in the list can be accessed from within the function. For example, if we create A Global function A, the [[Scope] attribute of A contains only one Global Object ), if we create A new function B in function A, the [[Scope] attribute of function B contains two objects, and the Activation Object of function A is located at the beginning, global objects are placed behind them. When a function is executed, an executable Object is automatically created and bound to a Scope Chain ). The scope chain is created in the following two steps for identifier parsing. First, copy the objects in the internal attribute of the function object [[Scope] to the Scope chain in order. Second, a new Activation Object will be created during function execution. this Object contains the definitions of this, parameters (arguments), and local variables (including named parameters, this Activation Object will be placed at the beginning of the scope chain. When executing JavaScript code, an identifier is searched in the scope chain of Execution Context based on the identifier name. Starting from the first Object of the scope chain (the Activation Object of the function), if not found, search for the next Object in the scope chain until the identifier definition is found. If the last Object in the search scope, that is, the Global Object, is not found, an error is thrown, prompting the user to undefined the variable ). This is the process of the function execution model and Identifier Resolution described in the ECMA-262 standard, and it turns out that most JavaScript Engines do. It should be noted that the ECMA-262 does not force the adoption of this structure, just to describe this part of the function. After learning about the Identifier Resolution process, we can understand why local variables are faster than variables in other scopes, mainly because the search process is greatly shortened. That is, when the process of identifier resolution requires deep search, performance loss will occur, and the degree of performance loss will increase with the increase of the depth of the identifier. Data Operations use local variables. The fastest obj. name is faster than obj. xxx. name, And the access attribute is faster, which is related to the depth of the object. The number of "." operations directly affects the time consumed to access object attributes. 2. frequently used objects, arrays, and related attribute values cached <span style = "font-size: 16px;"> function process (data) {var count = data. count; if (count> 0) {for (var I = 0; I <count; I ++) {processData (data. item [I]) ;}}</span> 3. do not directly operate NodeList, convert it to a static Array, and then use the method: Array. prototype. slice. call () => the standard browser copies one by one to a new array => For IE, it is important to note that when traversing NodeList, DOM operations that affect the current NodeList-related structure are not performed, as mentioned earlier, some attribute values frequently used must be cached to avoid unnecessary tragedies. Chestnut: <span style = "font-size: 16px;"> var divs = document. getElementsByTagName ('div '); // assume that there is a DIV in the page, so divs. length is for (var idx = 0; idx <divs. length; idx ++) {document. body. appendChild (// The Cup uses the document. createElement ('div '); console.info (divs. length) ;}</span> An error is reported when the code above is executed. insert the div node under the body, and the condition for ending the for Loop (div. length is also changed) invalid, into an endless loop. That is to say, what we get through getElementsByTagName () is a reference to Live NodeList, and any DOM operations related to it will immediately respond to this NodeList. Dom operation 1. add, query, modify, and try to use DocumentFragment to process nodes. You can use cloneNode () to copy a copy. to directly modify the DOM, first display: none; 2. specifies the context of the DOM operation. getElementsByTagName () 3. split method: One method solves one thing split function, so that one method can only do one thing and realize complex functions by constantly calling methods. However, these simple methods should avoid cross-call. Be Lazy (make the script run as little as possible or not .) Short-circuit expression application: for example, a & B | c writes the corresponding processing method based on the event. The inert function throttling <span style = "font-size: 16px; "> if (...) {} elseif (...) {} elseif (...) {} elseif (...) {} elseif (...) {} elseif (...) {} else {}</span> principle: In an if statement, when the condition that frequently occurs is placed on the top of the if statement is a continuous interval, you can use the binary method to split multiple discrete values, you can use switch to replace the array query method. Pay attention to implicit type conversion and careful recursion <span style = "font-size: 16px;"> var foo = 0; if (foo = false) {// implicit conversion ...} </span> <span style = "font-size: 16px;"> function recurse () {r Ecurse () ;}recurse (); // It is a tragedy and an error is reported. Infinite recursion </span> what is Reflow in reflow? That is: there is a rendering Object Concept in the CSS specification, which is usually expressed in a box (rectangle. Mozilla uses a frame object to operate the box. There are three main actions of frame: Construct a frame to create an object tree (DOM tree) reflow to determine the object location, or call mozilla's Layout (which refers to the implementation of source code) draw so that the object can be displayed on the screen. In general, reflow is a process of loading the content tree (DOM tree in HTML) and creating or updating the response of the frame structure. The reason for the reflow is that the style changes related to the layout of the DOM tree change the size of the className window and adjust the word break size. Therefore, to improve the page performance, we should avoid the overhead of reflow.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.