JavaScript optimization and development tips

Source: Internet
Author: User
With the development of front-end technology, front-end services become increasingly heavy, which greatly increases the amount of JS Code. Therefore, to improve the Web performance, we need to focus not only on the page loading time, but also on the page operation response speed. Next we will discuss several ways to improve JavaScript efficiency. I. Network Optimization

YSlow has 23 rules. For Chinese characters, refer to here. These dozens of rules are mainly used to eliminate or reduce unnecessary network latency and compress the data to be transmitted to a minimum.

1) Merge and compress CSS, JavaScript, images, and static resource CDN Cache

By using the build tool Gulp, you can combine and compress the tasks during development.

The reason for merging and compression is: HTTP 1. x does not allow the arrival of multiple response data on a single connection (multiplexing). Therefore, a response must be completely returned before the next response starts to be transmitted.

That is to say, even if the client sends two requests at the same time and the CSS resource is ready, the server will first send the HTML response and then deliver the CSS.

CDN is used to allow users to access the nearest resource and reduce the transmission time.

HTTP2.0 has improved HTTP1.x in many aspects.

2) Put CSS on the top and JavaScript on the bottom.

CSS can be downloaded in parallel, and JavaScript loading may cause blocking.

However, there will still be exceptions in everything. If you place the in-row script after the style sheet, it will obviously delay the download of resources (the result is that the style sheet is downloaded completely and the in-row script is executed completely, subsequent resources can be downloaded ).

This is because in-row Scripts may contain code that depends on the style in the style sheet, such as document. getElementsByClassName ().

 
  

Script var content = ''; for (I = 1; I <1000000; I ++) content + = 'write page'; document. getElementById ('content '). innerHTML = content; script

The following is a Chrome tool:

There is still a lot of room for optimization. For details about the pre-loading principle, refer to picture pre-loading and lazy loading.

2) reduce branches

When writing business logic, logic judgments such as if else and switch are often used. if so many judgments are made each time, performance is easily affected.

Therefore, you can avoid excessive judgment in multiple ways.

1. inert Mode

This is what I saw when I checked JavaScript design patterns.

This reduces the repetitive Branch judgment during each code execution, and blocks the Branch judgment in the original object by redefining the object.

There are two kinds of inertia modes: the first is to execute the object method to re-define the object after the file is loaded, and the second is to re-define the object when the method object is used for the first time.

The company has a page to provide to a third-party APP, but eventually found that the third-party APP cannot use localStorage cache, and eventually had to be compatible.

However, to avoid making judgments every time a method is referenced, redefine it immediately after loading:

var getFn = function() { if (sore.enabled)  return sore.get; return cookie.get;}();var setFn = function() { if (sore.enabled)  return sore.set; return cookie.set;}();

2. Establish a ing relationship

The pop-up box prompts are often required on the page, and you will create one later, but there will be many styles in the pop-up box.

If you use the simple factory mode to create a cluster, you can easily determine the switch branch, and then assign different keys to the cluster directly. The cluster can be cached and initialized only once.

/*** Singleton mode */var factories = {}; var DialogFactory = function (type, options) {if (factories [type]) return factories [type]; return factories [type] = new iDialog (options) ;};/*** prompt box */var Alert = function (content, options) {var d = DialogFactory ('alert ', options); // return d ;};/*** confirmation box */var Confirm = function (content, options) {var d = DialogFactory ('Confirm ', options); // return d is omitted for other logics ;};

3) asynchronous third-party code Loading

Third-party code, such as Baidu statistics and sdks, can be added after the service resources are loaded.

/*** Baidu statistics settings */util. baidu = function (key) {global. _ hmt = global. _ hmt | []; (function () {var hm = document. createElement ("script"); hm. src = "// hm.baidu.com/hm.js? "+ Key; var s = document. getElementsByTagName (" script ") [0]; s. parentNode. insertBefore (hm, s );})();};

4) cookie and localStorage Cache

With the cache, you can reduce the communication with the server and perform local operations.

The company has a business of checking for violations. After adding a vehicle locally, You Need To directly select the vehicle you have added before entering the page again.

The best way is to cache it locally after it is added, and directly retrieve the cache next time.

5) event Delegation

Using Event delegation technology allows you to avoid adding event listeners to a specific node.

Event Listeners are added to their parent elements, which are triggered by event bubbling.

During development, elements are often dynamically added.

If you re-bind an event every time, there will be a lot of extra operations, and you only need to bind the parent level of the element once.

document.getElementById('ul').onclick = function(e) { var e = e || window.event,  tar = e.target || e.srcElement; if (tar.nodeName.toLowerCase() == 'li') {  tar.style.background = 'black'; }}

6) throttle and dejitter

Throttle: sets an execution cycle in advance. When the call action is at a time greater than or equal to the execution cycle, the action is executed and enters the next new cycle.

For example, the mousemove event, the resize and scroll events of the window object.

Debounce: this action is executed only after n milliseconds of the call. If the call is performed within n milliseconds, the execution time is recalculated.

For example, text input keydown events, keyup events, and autocomplete events.

The biggest difference between throttling and dejittering is the calculation of the last execution time. The famous open-source tool library underscore has two built-in methods.

When working as a system in the company, you need to fix the first column to the leftmost when rolling the table between the left and right to facilitate viewing.

In order to make the operation smoother, I used throttling here. Some browsers may experience choppy traffic, so we need to increase the cycle time.

Iii. Tips

1) print the variable in the mobile phone

When you move a page, you often need to debug fields, and you cannot use console. log. Every time alert is reached, you will not be able to see the content when it comes to objects.

You can only write a small method to print it out. JSON. stringify can be easily implemented through this method.

var print = function(obj, space) { space = space || 4; var html = JSON.stringify(obj, null, space); html = html.replace(/\n/g, '
').replace(/\s/g, ' '); var pre = document.createElement('pre'); var p = document.createElement('code'); pre.style.cssText = 'border:1px solid #000;padding:10px;background:#FFF;margin-bottom:20px;'; p.innerHTML = html; pre.appendChild(p); var body = document.querySelector('body'); body.insertBefore(pre, body.children[0]);}; print({a:1, b:'demo', c:{text:'content'}});

For more articles about JavaScript optimization and development tips in the previous section, please pay attention to PHP!

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.