On front-end cache optimization

About cache, it can be divided into the following categories:

① CDN cache

② DNS cache

③ client cache (memory cache, disk cache without request; Etag / Last-Modified304 requesting authentication required)

④ Service Worker cache and offline caching

⑤ PageCache with ajax cache

 

A, CDN cache

CDN can be understood as distributed in each county or township ticket outlets, users browse the site, CDN will choose a response to a user request CDN edge closest to the user node. The advantage is obvious (1) CDN node to solve the problem of cross-regional and inter-operator access, access latency is greatly reduced; (2) the majority of requests completed in the CDN edge node, CDN has played a diversion effect, reducing the source station load.

About CDN cache, after the local browser cache invalidation, the browser sends a request to the CDN edge node. Similar browser caching, CDN edge node also exists a caching mechanism. CDN edge caching node and service provider policies vary, but generally will follow the standard http protocol, the http response cache-control header: max-age field to set the time data cache CDN edge node.

When a client requests data from the CDN node, the CDN node determines whether the cached data has expired, when the cache data has not expired, then directly to the cached data back to the client; otherwise, the CDN node will send back to the source a request to the source station, from source station to pull in data, update the local cache, and returns the latest data to the client.

CDN service providers typically offer a cache-based CDN to specify the file extension, directory more latitude time, to provide users with a more refined cache management.

CDN cache refresh:

CDN edge node is transparent to the developer, compared to the browser ctrl + f5 to force a refresh of the local browser cache invalidation, developers can provide through the CDN service provider "Refresh cache" clean up the interface to achieve the CDN edge cache node the goal of. So developers after updating the data, you can use the "Refresh cache" function to force the CDN node to the data cache expires, to ensure that clients accessing, pulled down the latest data.

Two, DNS cache

DNS (Domain Name System): responsible for the domain URL into the server host IP.

DNS lookup process: first check the browser cache exists, there is no access to the local DNS cache, it does not exist, access to the local DNS server. Therefore, DNS is overhead, usually a browser to find the IP address of a given URL takes 20-120ms, before the DNS lookup is complete, the browser can not download anything from the host there.

TTL (Time To Live): represents the DNS lookup returns the records contain a survival time expired then the DNS records will be discarded. Browser also has its own DNS cache expiration time, this time is independent of the local DNS cache, also relatively short, such as chrome only about 1 minute.

DNS Performance Optimization Best Practices

When the client's DNS cache is empty, DNS lookup of the number of web pages is equal to the number of unique hostnames. So reducing the number of unique host names can reduce the number of DNS lookups.

And sometimes require multiple settings to increase the number of host DNS load balancing point, thus reducing DNS lookups and increase the number of hosts that a contradiction relationship, battle-DNS hostname set 2-4 is the best. More load balancing can be achieved in other ways, such as using nginx load balancing.

Three , the customer's browser cache policy side caching

1. Cache-control:max-age

Suppose your site quoted a script file year will not change, then want the browser to cache the script file, do not request every time the server returns the same content. This can save bandwidth costs and boosting performance.

cache-control setting file only needs to return the http header is set to: cache-control: max-age = 31536000. // can control the cache time

Standard specifies a maximum max-age value can not exceed one year, and because is in seconds, so the value is 31536000.

If this address is the same script www.haorooms.com/never-expire.js, so when the next each time the user requests the address, the browser will no longer be requesting server, but directly from the local browser take cache. Or until one year after the user manually cleared.

But found during script content need to change how to do? A request to change the file name like, for example, never-expire-v2.js.

cache-control is http1.1 features, cache-control as well as other information:

(1) no-cache: Do not read the files in the cache, the cache request to the web server to verify whether fresh, fresh cache is used.

(2) no-store: This field is very important, it represents the data temporarily stored in the hard disk is not only-if-cached: that is, when the client has a cache on the client using the cache, this is generally used when no network

(3) max-stale: as long as the cache max-stale time is not more than a specified time, use can be loaded. Can be used without the network situation must-revalidate: the same effect, but more stringent check every request caching and server source file, an agreement on the use of the cache, it is inconsistent to take up to date.

(4) s-maxage with the maxage, covering maxage / Expires, but only for the shared cache, a private cache is ignored. Bai public response may indicate any object (transmission request of the client, proxy servers, etc.) cache. private indicates that the response can only be a single user (possibly the operating system user, the browser user) cache, a non-shared, can not be the proxy server cache.

2. Expires

Expires also avoid setting up the browser and the server sends requests until time expires.

Note: Expires is http1.0 properties, cache-control than earlier, there are some drawbacks. Since the failure time is an absolute time, so when a client local time is modified, the server and the client time deviation becomes large, it will lead to confusion cache.

More than two buffers follow the principle of level three cache, cache-control and expires at the same time can be configured to enable or enable any of the server side, when at the same time enable high cache-control priority.

3. Last-Modified 304 consultations cache

To inform the server browser version of the current file, it sends a last modified time tag, for example:

Last-Modified: Tue, 06 Jan 2018 08:26:32 GMT

If the cache is 304 negotiation, verification steps are as follows:

① browser: Hey, I need jquery.min.js this document, if it is the Last-Modified: Tue, modified after 06 Jan 2018 08:26:32 GMT, please send me

② server: Check the file modification time

③ server: Hey, this document has not been modified after that time, you already have the latest version

④ browser: Great, I'll show it to the user

4. ETag

Etag and 304 similar, but the level is higher than the Last-Modified Some

Request process:

① browser: Hey, I need haorooms main.css of this document, there is no mismatch "61213-1762a-50bf790757204" this string

② server which checks ETag ...)

③ server: Hey, here is my version of "61213-1762a-50bf790757204", you have the latest version of the

④ browser: Well, then you can use the local cache

 

Four, Service Worker cache and offline caching

With Service Worker (hereinafter referred to as SW) norms and popularity, the cache may be used to provide an interface SW alternative HTTP caching. Of course SW function is powerful, in addition to buffering capability, but also offline, data synchronization, back-end compiler and so on.

A standard version of sw cache code should have the following snippet:

const version = '2';

self.addEventListener('install', event => {
  event.waitUntil(
    caches.open(`static-${version}`)
      .then(cache => cache.addAll([
        '/styles.css',
        '/script.js'
      ]))
  );
});

self.addEventListener('fetch', event => {
  event.respondWith(
    caches.match(event.request)
      .then(response => response || fetch(event.request))
  );
});

Network requests the first to reach SW script, if forwarded to http cache misses.

This code means that, in the install stage we will script.js SW and styles.css into the cache; in the request initiated fetch stage, to find a match within a URL to go through the cache of resources, return immediately successful, otherwise take the normal network request process.

But the content of the resource in the install stage where they come from? Still come from http cache. Such SW caching and HTTP caching may fall as before, said the inconsistencies in the version.

The solution is to make the request SW must authenticate to the server:

self.addEventListener('install', event => {
  event.waitUntil(
    caches.open(`static-${version}`)
      .then(cache => cache.addAll([
        new Request('/styles.css', { cache: 'no-cache' }),
        new Request('/script.js', { cache: 'no-cache' })
      ]))
  );
});

Not all browsers support cache configuration options, but we can by adding random numbers to ensure that each requested URL is not the same, so that indirect cache invalidation.

self.addEventListener('install', event => {
  event.waitUntil(
    caches.open(`static-${version}`)
      .then(cache => Promise.all(
        [
          '/styles.css',
          '/script.js'
        ].map(url => {
          // cache-bust using a random query string
          return fetch(`${url}?${Math.random()}`).then(response => {
            // fail on 404, 500 etc
            if (!response.ok) throw Error('Not ok');
            return cache.put(url, response);
          })
        })
      ))
  );
});

Five, PageCache with Ajax cacheable

PageCache that one solution to ajax caching facebook raised.

facebook design a framework to identify whether a page from the cache (guess: after the page is first loaded all the Ajax Callback Result caching and AJAX get the page content, based on BigPipe participate in local .Facebook page), if from the cache, by ajax required to update the update module (speculation: div id predefined callback handler and a corresponding desired page paid by the present js, and when the page is downloaded simultaneously downloading down).

It refers to three types of updates: incremental updates, user replication (for example, the user replies in a comment on a page) and cross-page updates (for example, in the message detail page to a message marked as read, does not need to be home unread messages is updated). The core idea is to be updated based on AJAX.

(1) Incremental Update: as long as the page from the cache, that all predefined update module to be incremental update

(2) User replication: a user operation through the recording and reproducing HistoryManager all marked as "replayable" operation in the cache page read

(3) Cross-page update: API sends a signal to the client will expire cached by the server identified as invaild Database. After obtaining a cache expiration information via ajax to update the information needs to be updated.

facebook passing reference to an updated Ajax to avoid page content changes / flicker trick is to first place need to be updated is set to blank, rather than directly update its contents.

Guess you like

Origin blog.csdn.net/u014322206/article/details/94589352