[] Front-end performance optimization performance optimization schemes to help you tidy up (full system)!

Foreword

The front is huge, including a variety of resources, HTML, CSS, Javascript, Image, Flash, and so on. Front-end optimization is complex, resources for all aspects of has a different way. So, what's the purpose of optimizing the front end?

1. From a client perspective, optimization can make the page load faster, operate more timely response to the user, it provides a more user friendly experience.
2. From the server perspective, optimization can reduce the number of page requests or to reduce the bandwidth occupied by the request, saves considerable resources.
  
In short, the right not only to improve the user experience to optimize the site and be able to save considerable resources.

There are many ways to optimize the front, where I organized into three major points, the first is the HTTP request level , the second is the program code level , and the third is the request source in response to the nearest source level .

A, HTTP request level

This strategy basically all front-end people know, but also the most important and most effective. They say they want to reduce HTTP requests, request that more in the end what will happen? First of all, there is the cost of each request, includes both the time cost also includes the cost of resources. A complete requests need to go through DNS lookup, the connection is established (established tcp channel, three-way handshake), sending data, waiting for the server and the server receives data such a "long" and complicated process, and finally the browser needs to resolve html , css rendering render DOM tree corresponding to generate, through a series of refluxed and redraw js performed to form the corresponding page to the user.

So the main way to reduce the number of HTTP requests include:

1. Reduce the number of HTTP requests (quantized)
(1) optimize the picture requests: When it comes to the number of requests, request that the page picture certainly can not get away, and a picture will be sent a request, the request for the amount of the picture, we can use CSS Sprites images will be integrated into a Da map, and then get through the background-position corresponding to the picture to use for requests, this is undoubtedly the request of several pictures into a request, of course, this also increases the bandwidth occupied by the request, so it can be considered the United States and there is a little lack of it; and the second is the picture of base64, base64 encoded picture is does not consume the number of requests, but be careful not to use more than 10k base64 picture as possible, because the larger the size of the picture, converted into base64 code the more greatly affect the quality of the code; the last one is the font icon , the icon is a font format Iconfont, this icon is not consumed by the request, but can usually be met at this stage of our project most small iCON → Alibaba icon library

(2) Resources merged with compression: if you can, as much as possible of external scripts, style merger, more into one. In addition, CSS, Javascript, Image compression can be carried out with the appropriate tools, often after compression can save a lot of space

(3) Image lazy load (Lazy Load Images): surely we know, like Taobao, the petals of this picture are particularly large sites do give a picture of the current page the user loads it? Clearly impossible, for this picture many pages are lazy loading processing to reduce the fold in the number of requests for a picture, but note here is to reduce the number of HTTP requests, does not mean you can let the pictures do not need to be loaded by lazy loading send a request, but when you enter the page, lazy loading mechanism by the load will give you part of the picture, rather than the current page of the images have to send a request; only when the user continues scrolling until next load subsequent pictures . As a result, when if the user is only interested in the contents of the first screen, and that the remaining pictures are saved on request. When briefly about the realization of the principle, which is the front end to get the response data back-end picture, picture address, first on the img notes data-srcon the property, then srcthe property is empty, then scroll with the page from JS monitor users, As long as the current picture to the visible area of the window will be data-srcin the picture address in srcthe realization of a picture display

(4) a reasonable set of HTTP Cache: Cache is a powerful force and appropriate cache settings can greatly reduce HTTP requests. At home, for example, when the browser cache when no assumption that access will issue a total of 50 requests, a total of more than 500 K of data, and when the second visit that is cached browser access is only 10 requests, a total of 20 K data. (It should be noted here that if direct F5 to refresh the page, then the effect is not the same, the number of requests is still the same in this case, but the requested server cache resource is 304 response, but Header no Body, can save bandwidth)
how we considered reasonable set? Little change in image, for example, resources may be directly provided by Expires HTTP Header in a long expire head; changes are not frequent but may become a resource can be used to do Last-Modifed request verification. As much as possible so that resources can be longer in the cache. While this is mostly backend setting, this would involve mark-to-back response, the reasonable set too much can reduce the front and rear side interaction, speed up page loading

2. The percentage reduction HTTP requests broadband (qualitative)
(1) Resources merged with compression (quantization already mentioned this earlier, here or write about it, you can understand the request to reduce the amount of consolidation, compression reduces the share of broadband request): If you can, as much as possible of the external scripts, styles are merged, into one more. In addition, CSS, Javascript, Image compression can be carried out with the appropriate tools, often after compression can save a lot of space

(2) avoid large picture (large volume) Request: Request the big picture is bound to slow, will affect the user experience, but the project has certainly not avoid loading several large images, then we can picture volume appropriate compression, careful not to affect the quality of the picture, such as fuzzy distortion, this general UI designer of these pictures will be processed; of course, if the company is not so clear division of labor, it may be necessary to complete the job of the front-end (so to will do, there are now software that can be done), but if you do not know how you deal with or compress the time or the emergence of quality problems, we recommend using SVG format image, which is not only the volume compared to other small-format images, the most important is an enlarged without distortion!


Second, the program code level

Code optimization level, is an essential quality of programmers, not only to enhance the specification on the maintenance of the code, but also performance improvements (high-quality code can not affect the performance of your letter!), Not much beep Lai Lai's see What are some ways:

1. style and script code location
(1) Put CSS and JS script set HEAD in the end: this we should all know here that the reasons → ① If the CSS somewhere else, such as BODY, then the browser has not been possible to download and parse CSS has already begun to render a page, which led to a jump from the page without CSS CSS state to state, the user experience is relatively poor. In addition, some browsers will start to render pages after the download is complete CSS, if CSS placed on the lower position will cause the browser to render delayed; ② after HTTP1.1 browser HTTP request is concurrently, a feature that makes it faster to load resources, however JS script loaded Shique block other resources, such as before the script is loaded, it is behind the images, style and other scripts in the blocked state until after the script has finished loading will begin loading. If the script is placed more forward position, the entire page loading speed will be affected thereby affecting the user experience. There are many ways to solve this problem, and the most simple and reliable way is to script the next move as much as possible, to reduce the impact of concurrent downloads.

2. HTML
(1) rational use of HTML5 semantic notes, and tags nested chaos, reduce useless notes; you should be asking with front-end performance optimization What is the relationship? Note that the DOM structure design is reasonable, it will reduce the speed of the browser when parsing HTML DOM tree (DOM structure if more complex, with more losses will be more performance when traversing), concrete can see this article → redraw the return

(2) Since the new API features HTML5 web storage is an important Web Storage, convenient offline Web applications. In addition, the new API with respect to the cookie also has the advantages of high safety, high efficiency, a larger space. Because each request would carry the cookie will still consume them so the number corresponding to the request, and session Storage and local Storage just can optimize it;

3.CSS
(1) In most people's minds, feel type of browser parses CSS selectors from left to right conduct, for example, #pic A { color: #444; }such a selector, from left to right if it is to resolve the efficiency will be high, because the first a scope ID selection put substantially defining lookup, but in fact resolve browser selectors is performed from right to left. As the above selectors, browsers must traverse to find the ancestors of each of the nodes A label, the efficiency is not as before as high as imagined; so since the browser is parsing CSS, then, should not we be writing CSS styles when not to there are deep nesting, this performance optimization, as mentioned above with HTML, CSS DOM tree is resolved in the browser when involved, writing a nested too deeply (either HTML or CSS structure) will always let the browser parses slows down;

(2) In the animation, the animation itself should be allowed to flow out of documents, thus reducing the page constantly redraw reflux, because the animation itself is in motion, if there is flow of the document, it will affect next to the layout, the browser will re this part of the computing element size and location involved; second is to use css3 hardware acceleration, allowing transform, opacity, filters these animations do not cause reflux redraw → About these can look at this article to redraw the return inside said very clear

4.Javascript
(1) reduction operation DOM node:
DOM operations should be a class action script most resistance performance, such as add, modify, or delete elements to the DOM DOM collection operation. If the script contains a large number of DOM operations will need to note the following:

a. HTML Collection (HTML collector, returns contents information is an array)
  in the script document.images, document.forms, getElementsByTagName () Returns a collection HTMLCollection type are, when most usually use it as an array to use, because it has a length property, you can use the index to access each element. But on access performance than the array to be a lot worse, because this is not a static set of results, it represents only a particular query, the query is re-executed each time you access the collection to update the query results. The so-called "access to the collection" includes a collection of read length property, access elements of the collection.
  So when you need to traverse HTML Collection, try it and then access into arrays to improve performance. If not into an array, please access it as little as possible, for example, when traversing the length property can be saved to a member of a local variable and then use local variables.
  
b. Reflow & Repaint
addition to the above point, DOM operations also need to consider the browser Reflow and Repaint, because these are the need to consume resources

c. frameworks are virtual DOM stage as Vue / React operation, the bottom frame through different algorithms for DIff DOM before and after comparison operation, which does not go into detail specific

(2) access variable data:
  data directly accessing comprises an amount of Javascript (a string, a regular expression), variables, array and object attributes, and wherein the amount of direct access to the local variables is the fastest, and an array of object properties the need for greater access to overhead. When the following conditions, it is recommended to put data into local variables:
  . A visit to any object property more than once
  . B times on any array member to access more than 100 times
Also, should reduce the depth of the object as well as an array of possible Find.

(3) reduce the scope chain to find (in this regard to issues related to design some of the content):
  previously talked about the scope chain to find the problem, and this is a problem particular to note in circulation. Please if you need to access variables not under the scope of this cycle in the cache before traversing the variables local variables and then traversing the end of the rewrite that variable, which is particularly important for global variables, because the global variable is in scope the top of the chain, the number of times when the visit is to find the most; we compare these two usages ↓
① inefficient wording:

// 全局变量 
var globalVar = 1; 
function myCallback(info){ 
for( var i = 100000; i--;){ 
//每次访问 globalVar 都需要查找到作用域链最顶端,本例中需要访问 100000 次 
globalVar += i; 
}
} 

② more efficient writing:

// 全局变量 
var globalVar = 1; 
function myCallback(info){ 
// 局部变量缓存全局变量 
var localVar = globalVar; 
for( var i = 100000; i--;){ 
// 访问局部变量是最快的 
localVar += i; 
} 
// 本例中只需要访问 2次全局变量
// 在函数中只需要将 globalVar中内容的值赋给localVar
globalVar = localVar; 
}

In addition, to reduce the scope chain should also look to reduce the use of closures.

(4) string concatenation
use in Javascript "+" sign to concatenate strings efficiency is relatively low, as will open up new memory and generate a new string variable, and then assign the result to a new variable stitching each run. In contrast more efficient approach is to use an array of join method, will soon need to splice the string in an array calling its join method to get the final result. However, because of the use of the array has a certain overhead, more so when the string when needed stitching can consider using this method; the second is the perfect template syntax ES6 KO this by "+" practices splicing, convenient and efficient

(5) Lazy Load Javascript (this can be understood as loaded on demand, such as the asynchronous loading Vue syntax, code division binding webpack)
  With Javascript frame popular, more and more sites are also used from the frame. However, a framework often include a lot of functions to achieve these functions are not needed every page, if you download the script does not require the claim to be a waste of resources - a waste of bandwidth and wasted time spent execution . The current practice are of two kinds, one is for those who traffic is particularly heavy pages tailored a dedicated mini version of the framework, the other is Lazy Load. The second way is to use the YUI, YUI in the implementation of, the initially loaded core module, other modules can be used only when necessary to wait until the load. The Vue is the syntax loaded asynchronously in the routing configuration, SPA single-page application is very common

(6) increase code utilization:
A What is code reuse (code coverage).?
I would say something popular, specifically self Goole. Code coverage refers to the currently loaded page document how many are actually using the activation (activation code that is in green, and red is pending activation code)
Here Insert Picture Description

b. how to see?
Here Insert Picture Description

The picture shows the love Fantastic Art Home when loaded by using the Show Coverage test it out, you can see by the red box out, 70% code coverage after iQIYI first screen loaded, very nb, there are more than 55 a pretty good;

c. how to optimize, how do?
One → page currently loaded code is not doped with other irrelevant pages, or inattention and avoid the page by splicing together a plurality of modules, each module then requests the same resource, the resource will cause a repeat request;

Second → asynchronous code, on logic and user interaction, the use of asynchronous processing code, the code can increase utilization, can be tested by coverage, when we interact successfully triggered, the corresponding asynchronous code will turn green, and asynchronous code can enhance the coverage, the final say now optimized front-end cache can not just simply consider this level, but also concerned about the level of utilization of the code;

Third → Recent heavy Vue3.0 not released yet? There is too little understanding partner should know Vue3.0 optimized "shake the tree Tree-shaking" feature, this feature can be powerful, he can not automatically recognize the code page in use are Shaking, of course, not to say that because of this so that everyone that is not to upgrade the Vue otherwise keep up the trend, after all, fresh-baked taro is very hot, it takes time; Webpack to configure this if you do not use Vue3.0 development, it can also be achieved by Tree-shaking function this can refer to → WebPACK official documents


Third, the source of the request source in response to the level of the nearest

The name is a mess I played, so do not care. Just know what is meant by the next on the line;

(1) CDN Acceleration: This service usually have specialized suppliers, simply place the money on the line; the main is to achieve the request source (such as a user on the project in Guangzhou, request data, CDN will resolve to get this ip address request) after the transmission request, in response to a source (reception request according to the CDN deployed later performed quickly assign ip address from the nearest server, and returns the corresponding data corresponding to the client) returns the response data;

Epilogue

This article from the three aspects of the various ways to optimize front-end to do a summary, these methods are basically front-end developers can learn and practice in the development process, the desire to help you; of course also possible to optimize the method Yes, but I did not mention or are they do not know, so courtesy of the brightest big brother figure it out, refueling ~

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https: //blog.csdn.net/Umbrella_Um/article/details/102546329

Published 134 original articles · won praise 80 · views 30000 +

Guess you like

Origin blog.csdn.net/Umbrella_Um/article/details/102546329