Js basics (five) - front-end performance optimization summary

Front-end performance optimization summary

Resource Optimization

Cache

The best resource optimization is not loaded resources. Optimization is the most effective means of caching. To be honest, although the client cache occurs in the browser, but the cache server to control mainly, our relationship with the front end is not great. But still we need to find out.

Cache includes a cache server and client-side caching, we talk about the client cache. The so-called client-side caching mainly http cache. http cache and the cache is divided into mandatory consultation cache.

Forced Cache

  • Expires(http1.0)

Use Expires in http1.0 forced to do in the cache. Exprires value of the data returned from the server expiration time. When this time is requested again when the request time is less than the return of cached data is used directly. However, due to the server and the client time to time there may be errors, which will also result in a cache hit error.

  • Cache-Control

Cache-Control has many attributes, meaning different attributes represent different.

  1. private: The client can cache
  2. public: the client and the proxy server can cache
  3. max-age = t: cache content will expire in t seconds
  4. no-cache: cache consultation is required to verify the data cache
  5. no-store: All the content is not cached.

Cache consultation

First browser request data, the server will respond with the identification data cache to the client, the client will back them to the cache. Again request, the client will cache identifier to the server, the server is determined based on this identification. If no failure, the status code 304 returns the browser to get this status code can be used as a data cache.

  • Last-Modified

Server in response to the request, it will tell the browser resources last modified

  • if-Modified-Since

When a browser requests to the server again, the request header will contain this field, followed by the Last-Modified obtained in the cache (last modified time). The server receives the request hair prior if-Modified-Since, compared with the last modification time of the requested resource, if the requested resource is greater than the last modified time is returned 304, browser obtains the resource from the cache. If less than the requested resource was last modified, it returns 200, and returns the latest resources, the browser for the latest resources from the server, and caches.

  • Etag

Each unique identification string generated by the resource server

  • If-None-Match

When the request to the server again, the browser request packet header will contain this field, behind the value obtained in the cache ID. When the server receives the message views If-None-Match found is compared with the unique identifier of the requested resource. If the same, indicating that the resource has not been modified, return 304, browser access to resources from the cache, if different resource description has been modified, then return to 200, and returns the latest resources, the browser for the latest resources from the server, and caches.

Last-Modified and ETag can be used together, the server will give priority to verify ETag, under the same circumstances, will continue to compare Last-Modified, before deciding whether to return 304.

If you use a front-end packaging tools, can be packaged in a file when the file is added to the version number or hash value, it can also distinguish whether the resource is expired.

Reduce http requests

  • Use CDN hosting static resources
  • Can help gulp, webpack and other packaging tools to merge files js, css and other compression
  • Pictures lazy loading, demand loading, scroll to the picture when viewing area before going Load picture
  • Small picture and it will not change the basic picture using base64 encoded and transmitted. base64 do not abuse, even after a small picture base64 encoding will generate long string, it will be counterproductive if abuse base64
  • Figure Sprite, Sprite Figure this is used only for basic picture does not change, because if a picture changes, will cause the entire map Sprite regenerate, if indiscriminate use would be counterproductive.

Reducing the volume of resource http request

  • With webpack, gulp compression tools such resources
  • Service is enabled with gzip compression (compression rate is very impressive, generally above 30%)
  • If a useful tool packaging, packaging optimization to do, public resources, extracting third-party code, no packaged library ...

Rendering optimization

Read the front js operating mechanism should know that enter the url from the browser, the page appears on the screen, what things have taken place (tcp handshake, dns, etc. are not resolved purview).
  • FPS 16ms less than 10ms frame rate to complete the best Google devtool View

If the browser to reach the 60 FPS, will appear relatively smooth, most monitors refresh rate is 60Hz, the browser will automatically refresh animation in accordance with this frequency.
According to FPS equal to 60 to calculate an average time of 1000ms / 60 = 16.7ms, so every time the rendering time can not exceed 16ms, if more than this time will be dropped frames, Caton phenomenon.

Timeline can in chrome browser developers tool to view the refresh rate, you can view all frame rates as well as the implementation of a time-consuming frame. Timeline of Tutorial:https://segmentfault.com/a/11...

In order to ensure the normal FPS, some rendering performance optimization is necessary. The following strategies are described related to the rendering optimization.

  • Try to do animation using css3

As we know, css faster performance than js, css they are able to use, do not try to achieve js

  • Avoid using setTimeout or setInterval, or to make use of high frequency requestAnimationFrame animating Dom operation.

Because setTimeout and setInterval can not guarantee the timing of the implementation of the callback function, it is possible to perform at the end of the time frame, resulting in dropped frames, but requestAnimationFrame can guarantee callback function is executed when the start of each frame of the animation
Chinese MDN address requestAnimationFrame of:https://developer.mozilla.org...

  • Complex computing operations using Web Workers

If you have require complex data manipulation, such as an array of elements traversing a sum, then the Web Workers in easy to do.

Web Workers allow JavaScript scripts to run in the background thread (similar to creating a child thread), while the background thread does not affect the main thread of the page. However, the use of threads created Web Workers can not manipulate the DOM tree.
More about Web Workers can view MDN Comments:https://developer.mozilla.org...

  • css on the head, js on the tail.

Read the front js operating mechanism should know how the page rendering is a process, not repeat them. css on the head avoid splash screen phenomenon generated html tree after re-layout, js generally greater impact on the page, usually on the last execution tail.

  • Event image stabilization (debounce) and the throttle (throttle)

For high-frequency event-triggered (mousemove, scroll) and other events, if left unchecked it will trigger many events in a short time.

Anti-shake function refers to the case of frequent trigger, only enough free time, to execute code once. Scene: E-mail registration input box, along with the user's input in real time to determine whether the correct mailbox format, when the first event trigger input, set the timer: a check in after 800ms. If only after 100ms, the timing is not the last executed, this time to clear the timing, retiming 800ms. Until the last input, the input is not followed immediately, this time of a recent input timing is complete, and finally perform the verification code.

const filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;  
$("#email").on("keyup",checkEmail());  
function checkEmail(){  
    let timer=null;  
    return function (){  
        clearTimeout(timer);  
        timer=setTimeout(function(){  
            console.log('执行检查');  
        },800);  
    }  
}  

It refers to a function expansion method js certain period of time to run only once. That would have to be performed 100 times in one second become one second to perform 10 times.
Scene: the actual scene throttling function, most listeners will be used when scrolling page elements events.

var canRun = true;
document.getElementById("throttle").onscroll = function(){
    if(!canRun){
        // 判断是否已空闲,如果在执行中,则直接return
        return;
    }

    canRun = false;
    setTimeout(function(){
        console.log("函数节流");
        canRun = true;
    }, 300);
};
  • Dom operations

Do front-end developers are aware of the operation is very time-consuming (measured over 30 * 30 sent an open table traverse add style). So try to avoid frequent Dom operations, if not avoid it as much as possible to do the optimization of DOm operation.

1.:缓存Dom查询,比如通过getElementByTagName('div')获取Dom集,而不是逐个获取。

2: 合并Dom操作,使用createDocumentFragment()
    var frag = document.createDocumentFragment()
    for (i<10) {
        var li = document.createElement('li')
        frag.appendChild(li)
    }
    document.body.appendChild(frag)
 3: 使用React、Vue等框架的虚拟dom(原理目前还不明白),可以更快的实现dom操作。

  • Try to avoid redrawing (rePaint) and return (reFlow)

If you are using js change the color or the background color of the element will trigger redraw, redraw the cost is quite expensive, because to all nodes in the DOM element check that the browser will change the visual effects in certain DOM elements.

If you change the size and position of the element reflux occurs, bigger overhead reflux, it triggers a certain position in the DOM element is changed, and it will recalculate the position of all the elements and the area occupied on the page, so then it will cause a certain part of the re-rendering the entire page or even page.

  • css3 hardware acceleration

When the browser rendering, will be divided into two layers: an ordinary layers and composite layers.

Within the general flow of the document can be understood as a composite layer, absolute, fixed layout although can flow out of the ordinary documents, but it is still a normal layer, hardware acceleration will not start. The above said redraw (rePaint) and return (reFlow) say is redrawn and return on common layer.

Composite layer starts hardware acceleration. A common layer and not in the same layer, the composite layer does not affect the common layer, if the element is raised to a composite layer, then that element, will not cause the common layer and redraw reflux, thereby improving rendering performance.

How to start hardware acceleration:

1. translate3d and translateZ

webkit-transform: translateZ(0);
-moz-transform: translateZ(0);
-ms-transform: translateZ(0);
-o-transform: translateZ(0);
transform: translateZ(0);

webkit-transform: translate3d(0,0,0);
-moz-transform: translate3d(0,0,0);
-ms-transform: translate3d(0,0,0);
-o-transform: translate3d(0,0,0);
transform: translate3d(0,0,0);

2. Use the opacity
needed to perform the animation process will create a synthetic layer, not the state before the animation after the start or end element will return

3. Use will-chang property
This property is less common, generally used with the opacity and translate

For webkit browser, enable hardware acceleration in some cases may cause the browser to frequent flashes or flickers, you can use the following method to eliminate:

-webkit-backface-visibility:hidden;
-webkit-perspective:1000;
If hardware acceleration, use the z-index with the use, because if this element is added hardware acceleration, and the index level is relatively low, then the latter element to other elements (level higher than the element, or the same, and releative absolute property or the same), changes default rendering composite layer, if not handled properly will greatly affect performance
  • Avoid forced synchronization jitter layout and layout

Browser rendering process is: js / css (javascript)> computing style (style)> Layout (layout)> draw (paint)> Merge Layers render (Composite)

JavaScript : JavaScript for animations, DOM element operation.
Style (calculated style) : determine what CSS rules for each DOM element should be applied.
Layout (layout) : calculates the size and position of each DOM element displayed on the final screen.
The Paint (drawing) : DOM elements are drawn in a plurality of layers of text, color, images, borders, shading, and the like.
Composite (Render layers were combined) : Layers were combined in the proper sequence and then displayed on the screen.

If you read in the js style attribute some value will be forced to let the browser once the layout is calculated, and then the return value, such as:

offsetTop, offsetLeft, offsetWidth, offsetHeight

scrollTop/Left/Width/Height

clientTop/Left/Width/Height

width,height

请求了getComputedStyle(), 或者 IE的 currentStyle

So, if you force the browser to execute the layout process before executing JavaScript script, which is called the genlock layout.
For example, the code below:

requestAnimationFrame(logBoxHeight);

// 先写后读,触发强制布局
function logBoxHeight() {
    // 更新box样式
    box.classList.add('super-big');

    // 为了返回box的offersetHeight值
    // 浏览器必须先应用属性修改,接着执行布局过程
    console.log(box.offsetHeight);
}

// 先读后写,避免强制布局
function logBoxHeight() {
    // 获取box.offsetHeight
    console.log(box.offsetHeight);

    // 更新box样式
    box.classList.add('super-big');
}

When JavaScript script runs, it can get to the element's style property values ​​are on, all the old values ​​of a picture. So, if you have changes to the elements and nodes before the current frame to obtain property, it will cause the browser must apply property changes, the result of the implementation of the layout process, and finally execute JavaScript logic.

If the layout repeatedly forced synchronization, will lead to jitter layout
example, the following codes:

function resizeAllParagraphsToMatchBlockWidth() {
  for (var i = 0; i < paragraphs.length; i++) {
    paragraphs[i].style.width = box.offsetWidth + 'px';
  }
}

作者:SylvanasSun
链接:https://juejin.im/post/59da456951882525ed2b706d
来源:掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

We know that the browser is to refresh the page in a frame, for each frame on a layout information is known.
Forced layout is to use js force the browser ahead of the layout, such as the code below:

// bed  每次循环都要去获取left ,就会发生一次回流
function logBoxHeight() {
  box.style.left += 10
  console.log(box.style.left)
}

// goog 
var width = box.offsetWidth;

function resizeAllParagraphsToMatchBlockWidth() {
  for (var i = 0; i < paragraphs.length; i++) {
    // Now write.
    paragraphs[i].style.width = width + 'px';
  }
}
  • DOMContentLoaded与Load

When DOMContentLoaded event triggered only when the DOM was loaded trigger DOMContentLoaded, this time style sheets, images, introduction of external resources have not loaded. The load is loaded and all resources will be triggered.

1. 解析HTML结构。
2. 加载外部脚本和样式表文件。
3. 解析并执行脚本代码。
4. DOM树构建完成。//DOMContentLoaded
5. 加载图片等外部文件。
页面加载完毕。//load
  • Visual optimization

Wait for the rational use of load time can eliminate the user a sense of restlessness loading gif action figure to a certain extent latency

Code performance

The impact on the performance of the code can be very flexible, but to develop a good habit of writing code and high quality code, will be subtle to improve performance, but also to improve their level. Ado, a direct look at some key points I summarize (because too much of this part of the knowledge point, we need a lot of time writing code summary).

  • Avoid Global Search

Local variables faster than global variables, because variables js find time now to find a local office role, can not find the step by step looking up.

// bad
function f () {
    for (...){
        console.log(window.location.href)
    }
}

//good
function f () {
    var href = window.location.href
    for (...){
        console.log(href)
    }
}
  • Looping Techniques
// bed 
for(var i = 0; i < array.length; i++){
    ....
}
// good
for(var i = 0, len = array.length; i < len; i++){
    ....
}
// 不用每次查询长度
  • Do not use for in traversing the array

for in the slowest, others are similar, which is used directly for the fastest cycle. for in just suited to traverse the object.

  • Use + '' instead String () it into a string variable
var a = 12
//bad
a = String(a)

// good
var a = 12
a = a + ''

There are many like this, such as using * 1 instead of parseInt () are all using the weak type js, in fact, this is not great for performance, the Internet was tested, carried out hundreds of thousands of times a variable conversion, only faster zero a few seconds.

  • Delete dom

Delete dom element To delete an event registered on the node, otherwise you will not be recovered memory, select removeChild and innerHTML = '' the latter try to choose between them, it is said removeChild sometimes can not effectively release node (specific unknown reason)

  • Acting handle events using event

Any event can bubble can be processed on the ancestor node, so that the situation for the child nodes need to bind the same event would not have separately to each sub-node add event listeners, but are elevated to the ancestor node processing.

  • Dom js generated by the object must append to the page

In IE, the amount dom js created if not added to the page, this memory will not be recovered

  • Avoid comparing null

Can be replaced using the following method null comparator
1. If the value is a reference type, then check using its constructor instanceof
2. If this is the base type, the type checking of typeof

  • Possible instead of using the ternary operator if else
if(a>b){num = a}
else{num = b}

// 可以替换为
num = a > b ? a : b
  • When the judgment condition is larger than in the case 3, if instead of using the switch

Because the execution speed switch faster than if, do not under IE, if the speed is about twice

First summarize so much, in fact, there are many performance optimizations, such as pre-loaded, the server rendering, css selector optimization and so on. And so have the opportunity to summarize

Guess you like

Origin www.cnblogs.com/jlfw/p/11978477.html