preface
-
Page at the fastest speed to get all the necessary static resources, rendering fast;
-
The server is not requested when static resources on the server are not updated.
-
When static resource update on the server requests the latest resource on the server, the load is fast.
-
Static resource loading speed
-
Page rendering speed
Let’s start with a diagram that summarizes what we’ll be covering in this article.
Common cache types
1. Browser cache
You can see all HTTP Response Header field definitions in the OFFICIAL W3C documentation. The main ones that are relevant to caching are the ones circled above:
-
Cache-control:
- Public: The response is cached and shared among multiple users.
- Private: the default, the response can only be used as a private cache (e.g., within a browser) and cannot be shared between users;
- No-cache: The response is not cached, but requests resources to the server in real time.
- Max-age: indicates the number of seconds between the request time and the expiration time, in seconds. Relative time interval based on request time (Date field) rather than absolute expiration time;
-
Pragma: there is only one Pragma: no-cache, which works exactly the same as cache-control :no-cache. (Cache-control: no-cache was only provided by HTTP 1.1, so Pragma: no-cache can make no-cache applied to HTTP 1.0 and HTTP 1.1.)
-
Expires: Specifies how long a cached page Expires in the browser, equivalent to a max-age in cache-Control, or overwritten by a max-age in cache-Control if both exist. If set to 0, the page expires immediately. And if this property is set multiple times on the page, take its minimum value.
-
Date: indicates the time and Date when the message is generated.
-
Last-modified/if-modified-since: indicates the time when the local file was Last Modified on the server. When the cache expires, the browser sends the last modified time of the cached page to the server. The server compares this time with the last modified time of the actual file on the server. If the time is consistent, 304 is returned and the client directly uses the local cached file.
-
Etag/ if-none-match :(EntityTags) is a URL tag that indicates whether the URL object has changed. It is usually the hash value of the resource entity. Like last-Modified, if the server verifies that the resource’s ETag has not changed (the resource has not been updated), it returns a 304 status telling the client to use the local cache file. Etag takes precedence over Last-Modified, and Etag is designed to solve problems that last-Modified cannot solve.
- The file may change periodically, but its contents do not change and the client is not expected to get again.
- If-modified-since The granularity that can be checked is s-grade;
- Some servers do not know exactly when a file was last modified.
-
If-modified-since: last-modified in response;
-
If-none-match: Etag in response (If present);
-
Cache-Control
-
Pragma
-
Expires
<meta http-equiv="Cache-Control" content="no-cache"/ > <! --> <meta http-equiv="Pragma" content="no-cache"/ > <! -- Compatible with HTTP1.0 --> <meta http-equiv="Expires" content="0"/ > <! Set resource expiration time to 0 -->Copy the code
Putting caching instructions into meta tags is not a good idea, because although browsers may read them, proxies won’t. For that reason, they are invalid and you should send caching instructions as real HTTP headers.
HTML5 Application Cache
A. Add the manifest file
-
The first line of the file must be CACHE MANIFEST
-
The line starting with # is the comment statement
-
The site cache cannot exceed 5M
-
File resource paths can be absolute or relative
-
Failure of any cache in the file list invalidates the entire cache
-
You can use the same Minifest file for your site or one per page
-
CACHE: Resource files that need to be cached. The browser automatically caches the HTML page with the manifest attribute.
-
NETWORK: wildcard characters can be used for files that do not need to be cached.
-
FALLBACK: An alternative file that cannot access the cache file. Wildcard characters can be used.
B. Server configuration
AddType text/cache-manifest .appcacheCopy the code
C. References in HTML
<html lang="zh" manifest="main.manifest">Copy the code
1, events,
-
cached/checking/downloading/error/noupdate/obsolete/progress/updateready
2. Execution process
-
Creating Application Cache with manifest (Creating Application Cache with manifest); Creating Application Cache with manifest (Creating Application Cache with manifest);
-
Application Cache Checking Event
-
Application Cache Downloading Event (Downloading Cache files)
-
Application Cache Progress Event (0 of 4)
-
…
-
Application Cache Progress event (4 of 4)
-
Application Cache Cached event
-
Document was loaded from Application Cache with manifest (read HTML files and other static resource files from the Cache for display)
-
Application Cache Checking Event Checking Event
- If yes, download the cached file again for next access (does not affect the current browser display).
- Application Cache Downloading Event (Downloading Cache files)
- Application Cache Progress Event (0 of 4)
- …
- Application Cache Progress event (4 of 4)
- Application Cache UpdateReady Event
- no
- Application Cache NoUpdate Event
-
Document was loaded from Application Cache with manifest (read HTML files and other static resource files from the Cache for display)
-
Application Cache Checking Event Checking Event
-
Application Cache Obsolete Event (delete all files from local Cache, no longer use Cache)
-
The Application Cache caches HTML documents that reference the manifest file by default, which is a pitfall for dynamically updated HTML pages (which can be avoided using tricky iframe embedding).
-
If one resource in the cache list fails to load, all files will fail to be cached.
-
If the resource is not cached and NETWORK is not set, it cannot be loaded. Therefore, wildcard configuration must be used in NETWORK.
-
After the cache is updated, only the manifest file can be loaded for the first time. Other static resources need to be loaded for the second time to see the latest effect.
-
The files in the cache manifest are not recached by the browser when they are updated.
- Update the manifest file: Change the version number or date of the comment.
- Through the Application Cache provided interfaces (Windows. ApplicationCache. SwapCache) to check for updates.
This feature has been removed from the Web standards, and while some browsers still support it, it may be discontinued at some point in the future, so try not to use it. Using the application caching capabilities described here is highly discouraged at this point; It is in the process of being removed from the Web platform. Please use Service Workers instead.
3, PWA (Service Worker)
Service worker is a programmable network proxy, allowing you to control how network requests from your page are handled.
-
Unable to access DOM
-
The synchronization API cannot be used
-
HTTPS protocol required (http://localhost or http://127.0.0.1 is also available)
Simple to use
<script>
navigator.serviceWorker
.register('./sw.js')
.then(function(registration) {// Registration successful}); </script>Copy the code
self.addEventListener('install'.function(event) {/* After installation... */ // cache. AddAll: add cache files to the file, such as a.css,b.js}); self.addEventListener('activate'.function(event) {/* After activation... */ // caches. Delete: update cache file}); self.addEventListener('fetch'.function(event) {/* After requesting the resource... */ // cache. Put Intercepts the request directly returns the cached data});Copy the code
Static /js/main.js is referenced in the index.html file, and service-worker.js is registered in main.js. In service-worker.js, we can see precacheConfig (cache list) and cacheName (version number) variables. Disconnect from the network and we see that the files in the precacheConfig list can still be loaded locally.
Update mechanism
4, LocalStorage
5. CDN cache
Update mechanism
prebrowsing
Preloading is a browser indication of resources that may be used in the future, some of which may be used in the current page and some of which may be used in some future pages. As developers, we know more about our applications than browsers do, so we can use this technology for our core resources.
-
Dns-prefetch: DNS prefetch, which tells the browser that we may fetch resources from a specific URL in the future. When the browser actually uses a resource in the domain, the DNS prefetch can be completed as soon as possible. This parameter is used when using third-party resources.
-
Preconnect: preconnect. DNS preresolution is completed, TCP handshake is performed, and transport layer protocols are established.
-
Prerender: Prerenders, preloads all the resources of a document, similar to opening a link in a hidden TAB page — downloads all the resources, creates DOM structures, completes the page layout, applies CSS styles, executes JavaScript scripts, and so on.
-
Prefetch: Prefetch. A resource declared using prefetch is a reminder to the browser, indicating that the resource may be used “in the future”. It is suitable for caching resources from other routing pages that may jump to. The loading time of a prefetch resource is determined by the browser, and generally has a low priority and is downloaded when the browser is “idle”.
-
Preload: indicates that the browser is proactively notified of the acquisition of key resources on the page.
prefetch & preload
compatibility
prefetchand
preloadIn terms of browser support, prefetch is supported by all basic browsers except Safari, but Preload, as a new specification, is less compatible, but Safari is slowly supporting this standard, such as safari advanced options in iOS
Experimental Webkit functionalityThe Link Preload option is already available in.
priority
Note: Prebrowsing is easy to use, but it is important not to use it too easily unless you know that you want to load a file that is browsing easily.
application
<Link prefetch href='/'><a>Home</a></Link>
<Link prefetch href='/features'> <a>Features</a></Link>
{ /* we imperatively prefetch on hover */ }
<Link href='/about'>
<a onMouseEnter={() => { Router.prefetch('/about'); console.log('prefetching /about! ') }}>About</a>
</Link>
<Link href='/contact'><a>Contact (<small>NO-PREFETCHING</small>)</a> </Link>Copy the code
Optimization of trying
1. HTML files
2, js/ CSS /img file
Versioning is now generally done by filename. Webpack naming generates hash values for file names based on file contents, and regenerates hash values only when the contents are changed. In this case, you can set the HTTP Headers to a larger cache time, such as max-age=2592000, to avoid the connection between 304 requests and the server.
// js
output: {
path: config.build.assetsRoot,
filename: utils.assetsPath('js/[name].[chunkhash].js'),
chunkFilename: utils.assetsPath('js/[id].[chunkhash].js'),
}
// css
new ExtractTextPlugin({
filename: utils.assetsPath('css/[name].[contenthash].css'),}),Copy the code
3, webfont
-
The web fonts file will be downloaded only when the browser finds @font-face in the CSS selector of DOMNode. At this point, the browser has already downloaded the HTML/CSS/JS file.
-
Telling the browser to download the font file before the browser knows it needs to load it will speed up the file download and page load.
-
React + + Mobx + Webpack
-
React-router single-page/bundle-loader dynamically loads/uses large WebFONT files
-
Do the HTTP Headers cache configuration above for static resource files;
-
All static resource files are controlled by Service Worker cache and loaded offline.
Dynamically loaded JS
-
index.ef15ea073fbcadd2d690.js
-
The static/js / 0.1280 b2229fe8e5582ec5. Js
-
static/js/1.f3077ec7560cd38684db.js
-
The static/js / 2.39 ecea8ad91ddda09dd0. Js
-
static/js/3.d7ecc3abc72a136e8dc1.js
webpackConfig.plugins.push(new PreloadWebpackPlugin({
rel: 'prefetch',}));Copy the code
The REL property can also select the preload/Prefetch mode. It comes out like this:
When visiting the page, you can see that, without affecting dom loading, the browser preloads several other JS that will be used later. When switching to the corresponding route, it will also directly access from cache, rather than request resources from the server.
The CSS file
Dynamic load routing CSS is not split separately but in the js of the route, so it can only be optimized with JS.
Webfont file
1. Write plug-ins
fontpreload-webpack-plugin
2. Use plug-ins
- Installing a plug-in
npm install fontpreload-webpack-plugin --save-devCopy the code
- Add the following HtmlWebpackPlugin to webpack’s config file:
const FontPreloadWebpackPlugin = require('fontpreload-webpack-plugin');Copy the code
webpackConfig.plugins.push(new FontPreloadWebpackPlugin({
rel: 'prefetch',
fontNameList: ['fontawesome-webfont'],
crossorigin: true,}));Copy the code
3. Packaging effect