JavaScript optimization and development tips and tips

Source: Internet
Author: User
Tags openid

JavaScript optimization and development tips and tips

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 ().

<Head> <link rel = "stylesheet" href = "css/all-normal.css" type = "text/css"/> 

The following is a Chrome tool:

3) Optimize DNS resolution to reduce redirection

When conducting a "Goddess selection activity", you need to access the user's openid in the middle. It takes several steps to obtain the user's basic information:

Get the code first, get the openid through the code, and then jump to the static page.

As the company divides the business into multiple groups, three groups are required to redirect multiple domain names.

It is a waterfall chart before optimization, but it is not the worst case. Sometimes it takes more than 10 seconds to access a static page and it is completely unacceptable. Four domain names will be redirected to the link:

The domain name that does not jump to the index is directly redirected to the operation domain name, reducing the jump of a domain name. The Code of each group is optimized, but the effect is still unsatisfactory, just a few seconds faster.

Finally, we found that DNS resolution took too much time to interact with the server! You have to add a record to the host of the server and direct it to the server by IP address.

Is the final optimization result. Although it cannot reach the second, it is acceptable at least:

Ii. JavaScript Optimization

1) image pre-loading

We used image pre-loading during the "Autumn mountain" activity. This activity contains more than 120 images.

The process is very simple, that is, answer questions, and finally share the comments.

 

 

It would be silly to load so many images at once. Finally, I decided to load some general images when loading the page.

At the time of answering questions, the current page will pre-load the images on the following pages to prevent the images from being directly displayed when accessing the page, and the images will also be properly merged.

Put the website address in the gtmetrix.com test. below is the final waterfall chart. We can find that all the images are behind other static resources, so that we can display the page to users as soon as possible:

The optimization is far from over. After simulating good 2G, good 3G, and 4G respectively in Chrome, the results are not ideal.

Good 2G:

  

Good 3G:

  

4G:

  

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.

I will give priority to localStorage. The following table is a comparison:

Cookie

LocalStorage

Data Lifecycle

You can set the expiration time to save permanently unless it is cleared.

Big Data

About 4 kb about 5 M

Communicate with the server

Each time it is carried in the HTTP header, performance problems may occur if too much data is saved using cookies.
Do not participate in communication with the server

Local Storage, as shown in the previous history:

LocalStorage supports IE8 in terms of browser compatibility.

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, '<br>').replace(/\s/g, ' '); var pre = document.createElement('pre'); var div = document.createElement('code'); pre.style.cssText = 'border:1px solid #000;padding:10px;background:#FFF;margin-bottom:20px;'; div.innerHTML = html; pre.appendChild(div); var body = document.querySelector('body'); body.insertBefore(pre, body.children[0]);};print({a:1, b:'demo', c:{text:'content'}});

2) chrome plug-in JSON-handle

Many of the data returned by the server is in JSON format. Generally, after writing it, You can provide an interface and some demo parameters.

After opening it in the browser, It is a string, but if you want to show it to someone, you have to format it. This plug-in is used for viewing.

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.