Front-end development performance optimization

Front-end performance optimization-resource preloading

When it comes to front-end performance optimization, we first think of file merging, compression, file caching, and server-side gzip compression. This makes the page load faster and users can use our web application to achieve their goals as soon as possible.
Resource preloading is another performance optimization technique, we can use this technique to inform the browser that certain resources may be used in the future.

Quoting Patrick Hamann's explanation:

Preloading is a hint by the browser to the resources that may be used in the future. Some resources may be used in the current page, and some may be used in some pages in the future. As developers, we know our applications better than browsers, so we can use this technology for our core resources.
This practice was once called prebrowsing, but it is not a single technology, it can be subdivided into several different technologies: DNS-prefetch, subresource and standard prefetch, preconnect, prerender.

DNS pre-resolution DNS-Prefetch
tells the browser that we may obtain resources from a specific URL in the future through DNS pre-resolution. When the browser actually uses a resource in the domain, it can complete DNS resolution as soon as possible. For example, if we may obtain images or audio resources from example.com in the future, we can add the following content to the tag at the top of the document:

1 When we request a resource from the URL, we no longer need to wait for the DNS resolution process. This technique is particularly useful for using third-party resources.

Mentioned in Harry Roberts' article:

A simple line of code can tell compatible browsers to perform DNS pre-resolution, which means that when the browser actually requests a resource in the domain, the DNS resolution has been completed.
This seems to be a very small performance optimization, and it seems not that important, but it is not the case-Chrome has always made similar optimizations. When you enter a short segment of the URL in the browser's address bar, Chrome automatically completes the DNS pre-resolution (or even page pre-rendering), saving vital time for each request.

Preconnect

Similar to DNS pre-analysis, preconnect not only completes DNS pre-analysis, but also performs TCP handshake and establishes a transport layer protocol. It can be used like this:

1 There is a more detailed introduction in Ilya Grigorik's article:

Modern browsers try to predict which connections the website will need in the future, and then pre-establish socket connections to eliminate expensive DNS lookups, TCP handshake and TLS round-trip overhead. However, the browser is not smart enough to accurately predict all pre-link targets for each website. Fortunately, in Firefox 39 and Chrome 46 we can use preconnect to tell the browser which pre-connections we need to make.
Prefetching

If we are sure that a certain resource will be used in the future, we can ask the browser to request the resource in advance and put it in the browser cache. For example, an image and script or any resource that can be cached by the browser:

1 Different from DNS pre-resolution, the real request is pre-fetched and the resource is downloaded and stored in the cache. But pre-fetching also depends on some conditions. Some pre-fetching may be ignored by the browser, such as fetching a huge font file from a very slow network. Also, Firefox will only pre-fetch resources when the browser is idle.

As mentioned in Bram Stein's post, this is a very obvious improvement in webfonts performance. Currently, font files must wait until the DOM and CSS are built before they start downloading. Using pre-fetching can easily bypass this bottleneck.

Note: It is a bit difficult to test the pre-fetching of resources, but there are records of pre-fetching resources in the network panel of Chrome and Firefox. It is also necessary to remember that the pre-fetched resources are not restricted by the same-origin policy.

Subresources

This is another prefetch method. The prefetched resources specified in this way have the highest priority and are performed before all prefetch items:

1 According to Chrome documentation:

rel=prefetch provides a low-priority resource preloading method for future pages, and rel=subresource provides a high-priority resource preloading method for the current page.
Therefore, if the resource is necessary for the current page, or the resource needs to be available as soon as possible, it is better to use subresource instead of prefetch.

Prerender

This is a nuclear weapon, because prerender can preload all the resources of the document:

1 Steve Souders wrote in one of his articles:

This is similar to opening a link in a hidden tab page-all resources will be downloaded, DOM structure created, page layout completed, CSS style applied, JavaScript script executed, etc. When the user actually visits the link, the hidden page is switched to visible, making the page appear to be loaded instantly. Google Search has used this technology in its instant search page for many years, and Microsoft also announced that it will support this feature in IE11.
It should be noted that you should not abuse this feature. You can perform pre-rendering only when you know that the user will click on a link, otherwise the browser will unconditionally download all resources needed for pre-rendering.

More related discussions:

All preloading technologies have a potential risk: the resource prediction is wrong, and the overhead of preloading (preempting CPU resources, consuming battery, wasting bandwidth, etc.) is high, so we must proceed with caution. Although it is difficult to determine which resources users will access in the next step, high-confidence scenarios do exist:

If the user completes a search with obvious results, then the results page is likely to be loaded.
If the user enters the landing page, then the successful landing page is likely to be loaded.
If the user reads a multi-page article or visits a paged result Set, then the next page is likely to be loaded.
Finally, using the Page Visibility API can prevent the page from being executed before it is actually visible.

Preload

Preload is a new specification. Unlike prefetch (which may be ignored), the browser must preload the resource:

1 Although the specification is not compatible with all browsers, the idea behind it is still very interesting.

to sum up

Predicting which resources the user will access next is difficult and requires a lot of testing, but the performance improvement this brings is obvious. If we are willing to try these pre-fetching techniques, it will definitely improve the user experience significantly.

  1. Reduce network latency and network requests.
    Avoid using landing pages for redirection.
    Redirection will cause additional HTTP requests, cause network delays, and slow down the rendering of web pages. Redirection may also cause additional DNS lookups, TCP handshake and TLS negotiation.
    Combine resources and reduce network requests
    . The most common way to combine resources is sprite.
    In addition, you can also merge CSS and JS code.

  2. Controlling the number of resource downloads When
    accessing a web page, the requested resources must be useful to avoid useless resource requests, such as:

  3. Extra jsfiles, cssfiles

  4. Extra picture request

  5. Extra font request

  6. Optimization of resource volume The resources
    used by the website are mainly:

Text resources, such as js, css and html;
image resources, various pictures
3.1 Optimization of text resources
First of all, of course, you have to write high-quality and concise code.
Secondly, for js files, html files, and css files, it is necessary to minimize the files, remove spaces and line breaks between texts, and replace variable names.
These tasks are generally carried out when the front-end project is packaged, such as:

HTML files use HTMLMinifier;
CSS files are packaged in Webpack, configure the loader to minimize;
JS files use UglifyJsPlugin plug-in; the
next step is to use GZIP to encode and compress the files.
Modern browsers can accept files in gzip format, all we have to do is to configure the server.
3.2 Optimization
of Image Resources Choose the right picture format.
Although it is often said that png pictures can better represent photographic images than jpge pictures, for many pictures, png format pictures are converted to jpeg format for the clarity of the picture There is no particularly big impact, but the volume can be greatly reduced.
Remove unnecessary metadata
Some photos taken will contain metadata, which is data describing the data. Metadata will describe the device information, timestamp, image size, etc. of the picture taken. This is not very important for some webpage pictures, so we can remove these metadata.
Try this website VerExif.
Reducing the size of the image In
some cases, even if a large image is used for the background of the <img> tag or label, its size in the actual web page is also very small. In this case, the use of a large image is a waste of resources. It is possible to reset the image size, such as changing a 1200 x 600 pixel image to 600 x 300 pixels.
Reduce picture quality
In some cases, reducing the quality of the picture does not cause any visual difference, but it can reduce a lot of volume.
There are many softwares that deal with image quality, such as:

XNConvert
ImageOptim
Resizelt
more reference here.

Image compression
Although gzip compression is not effective for images, there are still many software that can compress images without affecting the size and visual quality of the image, such as this website.
For more websites, please refer to [here](
http://enviragallery.com/9-be....

  1. Using HTTP caching
    Strictly speaking, this is also considered to reduce the number of requests, but the implementation is completely different.
    Using HTTP caching is to set an appropriate caching strategy, which can prevent the browser from repeatedly requesting resources from the server.
    HTTP caching is mainly about setting the correct response header information on the server side.
    There are two types of caching: strong caching and negotiation caching.

4.1 Strong caching
Strong caching means that the browser directly uses local resources without making requests to the server. There are two response headers involved: Expires and Cache-control.
Expires is the content of http 1.0, and its content is a specific time set by the server, such as Expires: Wed, 21 Oct 2015 07:28:00 GMT, no need to know too much.
Cache-control is a new header added by http 1.1, and its value is one or a combination of the following commands:

no-cache: Indicates that the browser can cache the content, but you must first confirm with the server. If the resource has not changed, you can directly use the browser's cache. Mutually exclusive with no-store;
no-store: indicates that the content is not allowed to be cached, including browsers and intermediate devices, such as proxy servers, etc., mutually exclusive with no-cache;
public: indicates that the cache can exist in browsers and intermediate devices, and private is mutually exclusive;
private: indicates that the cache can only exist in the client's browser;
max-age: the time range in seconds, indicating how long the cached content will expire. After the expiration date, the browser must download the resource again.
After setting the strong cache, the browser will use the locally cached content or verify the browser based on the returned header information for each request.

4.2 Negotiation Cache
When the server does not set a strong cache for resources, negotiation caching can be used. There are two ways to enable negotiation caching:

Last-Modified and If-Modified-Since;
Etag and If-None-Match;
The names of the two sets of header information are very semantic, which reduces the difficulty of understanding.

4.2.1 The Last-Modified and If-Modified-Since
server sets the Last-Modified response header to indicate the time when the resource was last modified. This value is a point in time. When the browser requests, it will bring a header If-Modified-Since, the value of which is the value of Last-Modified. The server compares the last modification time of the resource with the time indicated by If-Modified-Since, and returns 304 if it has not changed.

4.2.1 Etag and If-None-Match The
server sets the Etag response header to indicate the unique identification string of the resource. As long as the resource is modified, an Etag will be regenerated. When the browser requests it, it will bring a header If-None-Match, whose value is the value of Etag. The server compares the current Etag and If-None-Match values ​​of the resource, and if they match, it returns 304.

Article source: https://www.jianshu.com/p/4bb9eee3bd57

https://www.cnblogs.com/10manongit/p/12799757.html

Guess you like

Origin blog.csdn.net/weixin_39854011/article/details/111827027