High Performance javascript--Reading notes

Source: Internet
Author: User
Tags closing tag script tag

One: Load and execute

The 1.<script> tag is placed at the bottom of the page,</body> the closing tag, which ensures that the page has finished rendering before the script executes.

2. Merge scripts. The fewer <script> tabs in the page load faster.

3. Non-blocking Download script: defer (lazy load), async (asynchronous load), dynamic create <script> element download and execute, download JS code using XHR object and inject into the page.

Second, data access

Four basic data storage methods: Literal (primitive Type: string, Number, Boolean, object, array, function, regular, direct assignment without the value to the right of the new equation), variable, array item, object member.

1. The fastest access to literal and local variables, and relatively slow access to arrays and object members.

2. Local variables start at the scope chain, so accessing local variables is faster than accessing cross-scope variables.

3. Avoid using the WITH statement, which alters the execution environment scope chain and changes the depth of the variable.

4. Nested object members are used sparingly, which can significantly affect performance. Execute location.href faster than Window.location.href.

5. The deeper the property or method is positioned in the prototype chain, the slower it is to access it.

In general, you can save common object members, array elements, cross-domain variables in local variables to improve JS performance, because local variables access faster.

Object literals are more efficient than new object (): the {} literal can be evaluated immediately, and new object () is essentially a method call, so a scope resolution is required, and the object is created after the same name function is found.

Object literal vs Constructor Create object comparison ( literal advantage ):

A. Its code volume is less and easier to read;

B. It can be emphasized that an object is a simple variable hash table, without necessarily deriving from a class;

C. Object literals run faster because they can be optimized at parse time: they do not require scope resolution (scope resolution), because there is a possibility that we have created a constructor with the same name, object (), and when we call object (), The parser needs to look down the scope chain from the current scope, if a function named Object () is found in the current scope, and if it is not found, continue to look up the scope chain until the global object () constructor is found

The D.object () constructor can receive parameters that can delegate the creation of an object instance to another built-in constructor and return another object instance, which is often not what you want.

// Object Direct Volume definition var o = {  function  ([parameters]) {},  get Property () {},  set property (value ) {},};

Differences in object creation by object literals and constructors: 1190000008462406

Three: DOM manipulation

1. Minimize the number of DOM accesses, as far as possible on the JS side processing. (DOM render engine and JS engine are independent, interactive consumption performance) such as traverse. innerhtml+= ' A ' assignment, you can first put ' AA. ' The content is merged and then assigned at once.

2. If you need to access a DOM node multiple times, use a local variable to store its reference.

3. Handle the HTML collection with care (such as document.images,document.links returns a element) because it contacts the underlying document in real time. If you need to traverse, the collection length is cached to the variable, and if you need to manipulate the collection frequently, you can copy it into an array. The HTML collection in the DOM standard exists in real time in a "hypothetical real-time" state, and it is updated automatically when the underlying document object is updated, even if the number of collection elements is taken.

4. If possible, use a faster API such as Queryselectorall (return nodelist, which returns no HTML collection, so the returned node does not correspond to the real-time document structure. document.getElementById () is an HTML collection that needs to be copied into an array to get a static list similar to Qall) and Firstelementchild

5. Note Redraw (caused by non-geometric attribute changes.) and Reflow (When Geometry properties and page layouts change.) Reflow optimization: Optimizes the reflow process through queued modification and batch execution, but some methods force flushing of the render queue, such as offsettop offset/scrollleft scroll position/clientwidth series and calculate style values getcomputedstyle/ Currentstyle): Minimize reflow and Redraw "" Merge multiple changes to DOM and style; When you bulk modify styles, the "offline" operation of the DOM tree (off document: Display, document fragment, copy node), using cached layout information (offsets, etc.), and reducing the number of local information accessed.

6. Use absolute positioning in animations (reduce refresh of render queue), use drag-and-drop proxy ()

7. Use event Delegation (Target/screlement) to reduce the number of event handlers.

IV: Algorithm and Process Control

1. Use lookup tables faster than If-else and switch when judging conditions are high.

2. Browser Call stack size limits the recursive algorithm in JS application, stack overflow will lead to code interruption. You can change the iterative algorithm or Memoization (the method that caches the results of the operation) to avoid duplicate calculations.

Five: string and regular expressions

1. Do not consider IE7 array item merging is a slow string connection method, can be replaced with a simple + and + = operator, avoid unnecessary intermediate strings (ie, other browsers will try to assign the string to the left of the expression more memory, and then simply copy the second string to its end.) If the underlying string in the loop is located at the leftmost end, you can avoid duplicating a progressively larger base string Example: str + = ' one '; str + '-one ' can use str=str+ ' single ' + ' double ' to enhance performance, str as the basis, append a string to it each time. But if str = ' one ' +str+ ' one ', the optimization fails.

2. Regular-type processing of backtracking problems

Six: Quick-response user interface

1. Any JS task should not be executed for more than 100 milliseconds. Excessive uptime results in a noticeable slowdown in UI updates that affects the user experience.

2. You can use the timer to decompose large tasks into small tasks after execution, or use Webworker, which allows the execution of JS code outside the UI thread, thus avoiding locking the UI.

Seven: Quick-Response user interface

1. Choose the correct data format: Plain text and HTML only for specific occasions, can save the client CPU cycle; XML is well-supported but cumbersome and slow to parse, JSON lightweight, fast parsing, character-delimited custom formats are very lightweight, very fast when parsing a large number of datasets, However, additional server-side constructs need to be written and parsed on the client.

2. Data Request method

XMLHttpRequest (XHR): Data cannot be requested from the other side, the data returned from the server is treated as a string or XML, which means that processing large amounts of data can be slow. Without changing the state of the server, only requests for data are used get, and data that is requested with get is cached. Parameters more than 2048 characters can use a POST request.

Dynamic Script tag insertion: can request Var el=document.createelement (' script ') across domains, el.src= ';(' head ') [0].appendchild ( EL);

Disadvantage: Cannot set the request header, can only use the Get method, cannot set the request time-out processing or retries, whether the failure does not necessarily know. The response message is the source code for the script tag, and it must be an executable JS code.

Iframes

Comet:

Beacons: Like dynamic script injection, use JS to create an Image object and set src as the script URL on the server. Suitable for sending small amounts of data return information is less important

var New Image (); Beacon.src=url+ '? key1=value1 '; beacon.onload=functionif(this . Width==1) {// If the contract returns a picture width of 1 indicates success 2 means retry, if no return data is returned for a 204 no content it will prevent the client from continuing to wait for the message body to never arrive }Elseif(this. width==2) {///2 otherwise retry }} Beacon.onerror=function() {}

Multipart XHR: Allows the client to transfer multiple resources from the server to the client with only one HTTP request. Data cannot be cached

Note: Any data type can be sent as a string by JS.

3. Reduce the number of requests, can be by merging JS, CSS files or using MXHR;

4. Shorten the page load time, the main content of the page after the completion of loading, with Ajax to get the secondary file

Eight: Programming practices

1. Avoid using the Eval and Funciton constructors to avoid double evaluation (executing another piece of code in the JS code, at which point the value is evaluated in the normal way, and then a second evaluation operation is initiated during execution of the code that contains the string). Transfer functions to settimeout and setinterval instead of strings as arguments

2. Avoid duplication of effort (compatibility function for event handling). Lazy Loading (detection at script invocation) and conditional preloading (early detection during script loading) are available when the browser needs to be instrumented.

Lazy Loading:

function AddHandler (target,eventtype,handler) {       if (target.addeventlistener) {              AddHandler=function  (target,eventtype,handler) {                     Target.addeventlistener (Eventtype,handler,false)}}  Else{       function  (target,eventtype,handler) {              Target.attachevent ("on"+Eventtype,handler)}}   AddHandler (Target,eventtype,handler)}

Conditional preload:

var function (target,eventtype,handler) {                     Target.addeventlistener (Eventtype,handler,false)}: function (target,eventtype,handler) {              target.attachevent ("on"+Eventtype,handler)}

3. Consider the bitwise operation of the binary form of the operation number in the mathematical calculation

4. Use native methods as much as possible.

Nine: Build and deploy high-performance JS applications

1. Reduce the amount of HTTP requests by merging JS files

2. Compressing JS files

3. Compressing JS files on the server (GZIP encoded)

4. Cache the JS file by correctly setting the HTTP response header, forcing the browser to reload the specified file by changing the file name

5. js files are provided using the CDN (Content Delivery NETWORTK) distribution network, which not only improves performance, but also manages the compression and caching of files.

Ten: Build and deploy high-performance JS applications

1. Use network analysis tools to identify bottlenecks in loading scripts and other resources on the page, helping to determine which scripts require lazy loading, etc.

2. Minimize the number of HTTP requests and load the script as late as possible

3. Use the Profiling Tools to find out where the script is running slowly, check the time spent on each function and the number of times the function is called, and find out where to focus optimization by calling the stack itself for clues

Other:

In practice, code optimization, extracting reuse functions, reusing components and so on.

High Performance javascript--Reading notes

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.