High-performance JavaScript reading notes

Source: Internet
Author: User
Tags script tag chrome developer chrome developer tools

0. Organizational Structure

According to the introduction, the author divides the book into four parts:
First, the best way to load JS page (pre-development preparation)
Second, improve the JS code programming skills (in development)
Iii. Build and deploy (release)
Iv. Post-release performance testing and problem tracking (online problem optimization)
This kind of organizational structure is also in line with our development habits, first into the first part.

One, JavaScript loading

Cause: Loading of script scripts will block the browser from rendering the page and handle user interaction, and if the script is loaded too much, it will be blocked for a long time, causing the page to feign death.
Solution:

1. Script Location

Put it on the bottom.
At the bottom, you can ensure that the main structure of the page is loaded and displayed to the user before the script is loaded. This rule is also a special case, if it is some company's embedded script, may require to be placed in the head, to ensure that the page load duration.

2. Organizing scripts

Reduce the number of scripts and merge the script.
This can be achieved either by merging with the concat packaging tool or by a CDN-provided combo.

3. No blocking script

After the page is loaded, it will trigger the loading of JS, which prevents the script from loading the blocked page.

Native defer

The script tag comes with the defer attribute, which can be used to achieve this. Incidentally, the Async attribute can trigger asynchronous loading, making reasonable use of broadband.

Dynamic scripting

Or you can use dynamic scripting elements to dynamically create a script tag through the JS file, which is executed immediately after the file is loaded.

The point of this technique is that whenever a download is initiated, the download and execution of the file does not block other processes on the page.

XMLHttpRequest Script Injection

With the XHR load script, you can control the code execution time in the script tag because it is not loaded in the script tag. Add the script tag to the page when you need it.
This is also the principle of JSONP.

Non-blocking mode recommended by authors

Load a small amount of Jsloader code first, and then load the remaining code through loader.

function Loadscript(URL,Callback{    varScript= Document.createelement(' script ');    Script.type = ' Text/javascript ';        if(Script.readyState){ //IE        Script.onreadystatechange = function(){            if(Script.readyState == ' Loaded ' || Script.readyState == ' complete '){                Script.onreadystatechange = NULL;                Callback();            }        }    } Else { //Other browsers        Script.onload = function(){            Callback();        }    }        Script.src =wr.;    Document.getElementsByTagName(' head ')[0].appendchild(script);}Loadscript(' Rest.js ', function(){    Rest.Init()});
YUI3, Lazyload, LABJS

The author introduces the use of Lazyload in the above 3 class libraries, in fact, the principle is said above, in the experience has different. The key is to listen to the script onload event in loader to determine the timing of the script execution.

Second, high-performance programming skills

This section describes different techniques for improving performance, from 2 to 8 chapters respectively.

1. Data access
    There are four ways to access
    • data, such as literals, variables, data items, and objects. Literals and variables are faster than array items and objects. The
    • local variable is at the beginning of the scope chain, finding the fastest, the deeper the location, the slower the lookup, and the slowest global variable lookup.
    • with can affect the scope chain, and the catch in the Try-catch statement also affects. Use cautiously.
    • If the current object does not have a property or method, it will traverse the properties and methods on the prototype chain, as well as result in performance loss. The more nested object layers of the
    • , the slower the speed. For example, Location.href is faster than window.location.href.

    • Workaround:
      Most of the performance losses are related to object lookups, so it is recommended that you cache objects to reduce the number of lookups.

      2.DOM Programming
    • because the DOM rendering engine and the JS engine are generally separate implementations, to allow two of independent modules to establish communication, it will incur consumption. So, we need to reduce DOM operations, the DOM nodes that have been fetched, and cache them down to prevent repeated operations.
    • Second, note redrawing and reflow, which actions on the DOM cause redrawing and rearrangement, reducing this.
      Finally, you need to be aware of DOM events handling user interaction.

    • uses innerHTML and native document.createelement () in a similar way, with little difference in speed. In addition to the latest version of the WebKit kernel browser (chrome and Safari), the innerHTML will be faster and, in comparison, much less code. The

    • HTML collection is a method that contains a class array object referenced by a DOM node, such as Document.getelementbyname (), and it is important to note that the HTML collection remains connected to the document, and each time new information is needed, will be queried again.

    • When looking for DOM elements, use native methods as much as possible, such as the latest support for the more sophisticated Queryselectorall ().

    • reflow is required when page layout and Geometry properties change, for example:
    1. Add or remove visible DOM elements
    2. Element position Change
    3. Element size changes (including: margin, padding, border thickness, width, height, etc.).
    4. Changes in content, such as text changes or images replaced by another size
    5. Page Renderer Initialization
    6. browser window size Change
    • In order to reduce reflow and redraw, when you bulk modify styles, the "offline" operation of the DOM tree, using caching, and reducing the number of access to layout information. Use absolute positioning in animations, using drag-and-drop proxies.

    • Use event delegates to reduce the number of event handlers.

3. Algorithm and Process Control
    • Reduce the amount of iterations, such as using local variables to cache the length of an array, to reduce the number of queries.
    • Reduce the number of iterations, using Duff ' s Device.
    • As much as possible without forin,forin than for, while, do-while slower.
    • Switch is faster than If-else, but consider code readability in a comprehensive.
    • Lookup tables are faster than if-else and switch when judging the conditions.
    • Recursion easily causes stack overflow, which controls the number of recursive loops.
4. Strings and Regular expressions
    • When connecting a huge string, the array items are merged at IE7 or earlier versions are the best method.
    • If you are in a modern browser, it is recommended to use the simple + and + = operators Instead, avoiding unnecessary intermediate strings.
    • Backtracking is the basic component of regular, and it also brings performance problems.
    • Backtracking occurs where the regular expression should be quickly matched, because some special string match actions cause a slow run or even a browser crash. In order to avoid this situation, the neighboring characters should be mutually exclusive, avoid nesting quantifiers to match the same part of the same string multiple times, and eliminate unnecessary backtracking by using the pre-checked atomic group.
5. Quick-Response User interface
    • Any JavaScript task should not exceed 100ms, otherwise the user experience will become worse.
    • There are differences in the behavior of the browser in responding to user interaction during JavaScript operation.
    • Timers can be used to schedule code delay execution, but not necessarily accurately.
    • Web worker allows programmers to execute JavaScript code outside the UI thread to avoid locking the UI.
6.AJAX
    • Reduce the number of requests
    • Shorten page load time, the main content of the page after the completion of loading, using AJAX to get secondary content
    • Code error masking to users as much as possible
7. Best Practices
    • Avoid using the Eval and function constructors to bring the performance loss of double evaluation.
    • Direct volume creation of objects and arrays with direct volume
    • Avoid duplication of effort, and you can use lazy loading or conditional preloading when you need to detect a browser.
    • When doing mathematical calculations, consider using bit arithmetic.
    • Try to use native methods
Iii. Build and deploy
    • Merging JavaScript files to reduce the number of HTTP requests
    • Use Yui compressor to compress JavaScript files (in fact, today Nodejs tools are more useful)
    • compressing JavaScript files on the server (GZIP encoded)
    • cache JavaScript files by correctly setting HTTP response headers to avoid caching problems by adding timestamps to filenames
    • Using CDN
Iv. Post-release performance testing and problem tracking
    • Use the Network analysis tool to find bottlenecks in loading scripts and other resources on the page.
    • Lazy loading of scripts can speed up page rendering, resulting in a better user experience
    • Use the Profiling Tools to find out where the script is running slowly, check the elapsed time of each function, and the number of times the function was called, and find out where to focus the optimization by invoking some clues on the stack itself.
      Some tools:
    • YUI profile
    • Firebug
    • Page speed
    • Fiddler
    • Yslow
    • DynaTrace Ajax Edition

In fact, the functionality of these tools is available in the new version of Chrome development tools, so I recommend learning the chrome developer tools well.
Thanks for reading.

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.