preface

Performance optimization is a very grand proposition, whether it is big or small company, for make faster page displayed in front of the user to do optimization and exploration, page performance and test a front-end engineer project results important indicators, therefore, to the interview or not, the commonly used means of performance optimization is to grasp skilled.

In the first two articles front-end engineers must see the server knowledge, trace back to the source browser rendering mechanism, detailed introduction to the URL from the input to page rendering middle technical details, this article we summarize, commonly used performance optimization operations. For performance tuning during the build phase, refer to this webpack tutorial (ii) performance tuning Best Practices.

Figure god save

Reducing HTTP requests

Reducing the number of HTTP requests to a page is a starting point, and an important guideline for improving the speed of first visits to your site. Small print comes first.

Merge scripts and stylesheets

Merge CSS and JS files. The size of large files should not exceed 33KB (not all in one package). Keep the number of files appropriate.

CSS Sprites

Is the preferred way to reduce the number of image requests. Combine all the background images into one image, and then use the BACKground-image and background-Position properties of the CSS to locate the part to be displayed.

Inline images (Base64 encoded)

Use the Data: URL pattern to embed images on a page. This increases the size of the HTML file, putting inline images in a (cached) stylesheet is a good idea, and successfully prevents the page from becoming “heavy.” However, inline images are not well supported by mainstream browsers.

Configure multiple domain names and CDN acceleration

Typically, browsers have a limited number of concurrent requests for a domain name, such as 100 files to load, but browsers can only request 10 files concurrently at a time, which would be time-consuming. Therefore, configuring multiple domain names maximizes the number of concurrent requests.

However, there is a disadvantage that it will increase the number of browser domain name resolution. It is recommended to use CDN to load static resources (images, CSS libraries, JS third-party libraries, etc.) that are not updated and modified frequently. One is that CDN domain names are generally cached in the local, and the other is that the CDN network request speed is very fast.

Caching strategies

Caching resources is the most immediate means. By setting cache attributes in the request header, the next access can directly obtain resources from the local, reducing unnecessary data transmission, saving bandwidth and reducing the burden of the server. Improved site performance, faster client loading of web pages, strong cache and negotiated cache content can be seen before the front-end engineer must see the server knowledge.

Cache priority: cache-Control > Expires > Etag > last-Modified

On the first request, the browser checks for cache Settings and writes to memory. On the next request, the server decides to return 304 cached and 200 fetched from the server.

cache-control

Set the expiration length (in seconds) within which the browser reads the cache directly, and cache-control takes precedence when both expires and cache-control are present.

expires

Set an expiration date in the HTTP header, before which browser requests will not be issued, files will not be read from the cache, unless the cache is cleared, or forced to refresh. The flaw is that server time and client time may not be consistent, so http1.1 introduced cache-control to improve.

etag

When the server returns a resource with an eTAG in the header, the resource automatically adds the value to the if-none-match header in the next request. The server can compare this value to determine whether the resource has changed. If there is no change, 304 is returned.

last-modified

If the server returns a resource with last-modified in the header, the resource request will add the value to if-modified-since. The server can compare this value to determine whether the resource has changed and return 304.

Transfer load optimization

Start the gzip

Configure gzip: on in nginx

If zip compression is not enabled, we can compare the corresponding file size, as shown below:

Now that we have turned on gzip for the compressed file size, we can see something like this:

And when we look at the response header, we see compression like gzip, as shown below

This compression ratio is very objective and greatly improves the efficiency of the page.

Keep-Alive

Add Connection: keep-alive to the HTTP request header to tell the other party not to close the request after the response is complete, and we will use this request to continue communication next time.

Keep-alive is enabled by default in Http1.1. Connection: keep-alive can be seen in the Response Header.

There are two important configurations in nginx configuration

keepalive_timeout 65  // The time to hold the connection, also called timeout, in seconds
keepalive_request 100 // Maximum connection limit
Copy the code

Browser request //xx.cn/a.js–> resolve domain name -> HTTP connection -> server process file -> Return data -> browser parse, render file. This is the core problem that Keep-Alive solves. Within a certain period of time, the same domain name requests data for several times and establishes only one HTTP request. Other requests can reuse the connection channel established each time to improve the request efficiency. Certain times can be configured,

HTTP1.1 still has efficiency issues

  • Serial file transfer
  • Too many connections

HTTP/2 is stream-based for all requests under the same domain name, which means that no matter how many files are accessed from the same domain name, only one connection is established. Also, Apache’s maximum number of connections is 300, because with this new feature, the maximum number of concurrent connections can be increased to 300, a 60-fold increase!

Lazy loading

Loading images only in a visual window greatly improves first rendering speed! Native support Loading requires browser support

Third-party plug-ins

  • lazyload (opens new window)
  • react-lazyload(opens new window)

Performance optimization in rendering

In the last article we saw that the browser generated four trees during rendering

  • GUI threads and JS threads areThe mutexthe
  • Rearranging and redrawing is a performance drain

Put style sheets at the top and JS files at the bottom

Yahoo military rules, style sheets at the top, JS files at the bottom, the meaning of this is to avoid fighting, harmony between the two men.

Reduce rearrangement and redrawing

Chrome DevTools can detect page rendering performance analysis using keyFrames. To achieve an animation effect.

<div class="container">
  <div class="ball" id="ball"></div>
</div>@keyframes run-around { 0% { top: 0; left: 0; } 25% { top: 0; left: 200px; } 50% { top: 200px; left: 200px; } 75% { top: 200px; left: 0; }}Copy the code

Check with Chrome DevTols

  • Loading: Network communication and HTML parsing
  • Scripting:JavaScript execution time
  • Rendering: computing and Layout layouts
  • Painting: redrawn

See that the browser is constantly rearranging and redrawing the composition cycle

We use Transfrom to replace absolute positioning for GUI acceleration.

0% {
  transform: translate(0.0);
}
25% {
  transform: translate(200px, 0);
}
50% {
  transform: translate(200px, 200px);
}
75% {
  transform: translate(0, 200px);
}
Copy the code

The recording again

We can see the sharp contrast, skipping the rearrangement and redrawing process, greatly improving the performance of the page

requestAnimationFrame

Animation operations can use requestAnimationFrame to ask the browser to call the specified callback function to update the animation before the next redraw, which can be synchronized with the browser to avoid unnecessary overhead.

Yahoo! Catch

Yahoo developed 8 parts, 35 performance optimization criteria, part of this article from the military rules in detail, details can see 'reference link'.Copy the code

Page loading performance indicators

Consider a question 🤔, after we carry out performance optimization, how to evaluate whether our optimization means meet our business, whether there are quantitative standards to help us analyze whether there are shortcomings, accurate positioning to the problem

Phase – describe Stage (full name)
TTFP First byte time Time TO Frist Byte
FP First draw (first node) First Paint
FCP First content drawing (skeleton) First Contentful Paint
FMP First meaningful draw (with all elements/data) First Meaningful
TTI Reach the interactive time, the recommended response time is less than 100ms otherwise there is a delay Time To Interactive
Long tasks Tasks over 50ms
SSR&&CSR Server-side rendering and client-side rendering Server-Side-Rendering / Client Side Rendering
Isomorphic TongGouHua

Take an H5 page opening as an example

Monitor FP, FCP, FMP, TTI with Chrome panel

SPA Performance Issues

The usual React/Vue code is packaged as follows:

With only one root node, the DOM is parsed by JS to generate a virtual DOM -> DOM diff -> page

Solution: YOU can use SSR server rendering to fill in the HTML content, but at the cost of TTFP time.

summary

Just as we frantically press the close button in the elevator, users are impatient to wait for a page to load, and a poor performance page is easy to lose users.

This paper carries on the above two articles, makes a summary of the whole process, analyzes the steps that can be optimized in the middle, of course, here is just as many optimization schemes as possible, the reference link will give some better optimization, performance optimization has a long way to go, this paper will continue to update.

Refer to the link

Thoroughly understand strong and negotiated caches

Yahoo catch 35

Summary of front-end performance optimization

Summary of Web front-end performance optimization

Seven tools for front-end performance optimization

Nginx cache configuration and enable gzip compression

Mobile Taobao performance optimization

Front-end performance optimization – Reduce HTTP requests

xikun’s blog