Performance is a very important part of front-end development. Different from applications, all resources of web pages initially need to be transmitted through the network. Therefore, how to better carry out network transmission has a great impact on front-end performance, in addition to the optimization of browser rendering. However, how to optimize front-end performance is a constant topic. This article is based on my previous understanding after reading the principles and practices of front-end performance optimization. For more details, please refer to the booklet.
The original link
Overview file: Front-end performance optimization.xmind.zip
An overview of the
What are the aspects of performance optimization? We need to understand how the browser opens the web page.
- The browser resolves the URL by DNS
- The browser connects to the server through TCP
- The browser makes an HTTP request
- The server returns an HTTP response
- The browser renders the page
Let’s optimize each of these phases.
The browser performs DNS resolution
DNS Full Name Domain Name System. It is the Internet’s “address book”, which records the relationship between domain names and actual IP addresses, domain names are for human memory. Every time we visit a website, we have to query the server IP of the website through DNS servers at all levels before we can access the server.
Resolving DNS in advance
DNS prefetch technology is used to resolve DNS in advance. It can be used in HTML
<link ref="dns-prefetch" href="">
Copy the code
Form tags to pre-resolve a specific domain name, which the browser does after the page has loaded
Alternatively, you can use the X-DNS-prefetch -Control: on/off response header to Control the switch of preparsing. It can be used in HTML
<meta http-equiv="x-dns-prefetch-control" content="on/off">
Copy the code
To achieve this effect or simply have the server return the response header.
The TCP connection is set up with the server
TCP Transmission Control Protocol. Is a connection-oriented, reliable transport protocol that resides at the transport layer of the OSI model.
The browser sends an HTTP request
Reduce the number of requests
-
Resources combined
-
Use the packaging Tool
Use tools such as Webpack to package JS and CSS resources to avoid excessive JS or CSS files.
However, we also need to consider the problem of packaging files too large, which needs to be considered comprehensively.
A common practice in SPA is that common files extracted by Webpack are loaded first, and routing related files are loaded on demand.
-
The elves figure
The combined image of multiple small graphs.
Use background-position for positioning.
-
-
The cache
-
HTTP Cache
-
Strong cache
The specificity of strong caching is that there is no need to ask the server, which is achieved through Expires and cache-control. Cache-control takes precedence over Expires, both of which are used to indicate an expiration date. Expires is a store timestamp, and cache-Control uses max-age to indicate a relative time.
Cache-control’s no-cache does not ask the browser, but requests the server directly (for negotiated caching). No-store does not use any caching strategy. S-maxage takes effect only on proxy servers.
If the resource has not expired, it is used directly.
-
Negotiate the cache
The negotiated cache is a request to the server, and the server decides whether to return a new resource or tell the browser to use the old resource.
Each time the server returns a resource with a last-Modified timestamp and each request with an if-Modified-since timestamp, the server determines whether the resource has been Modified at the same time.
The problem with last-Modified is that even though the server file changes at a different time, the file content doesn’t really change
All have eTags, which are unique identifiers calculated from the contents of the file. The request is matched with if-none-match for the server to determine
-
-
Service Worker Cache
-
Memory Cache & Disk Cache
They work with HTTP caching. Memory cache hits are the fastest, but it has a short cycle. Base64 images, smaller JS and CSS have a greater chance of being written into memory. Other large JS, CSS and images are written directly to the hard disk for caching.
-
-
Storage (detailed explanation)
-
cookie
Cookies, with a maximum size of 4K, are usually used to store some user login status. For each request, the browser will bring cookies under the same domain name
-
webStrorage
Webstorages are divided into two types, sessionStorage and localStorage, which are between 5 and 10 meters in size. Are stored as key-value pairs. SessionStorage differs from localStorage in life cycle. SessionStorage ceases to exist after TAB closure, while localStorage permanent storage, unless actively deleted
-
indexDB
Browser end “database”, because at present basic useless, all temporarily do not study
-
Reduce request volume
-
Resources compression
-
Gzip
You can enable gzip compression on the server to reduce the size of the transferred file, as can be seen in the response header Content-Encoding: gzip.
-
Code compression
Use some code compression tools to reduce file size by removing unnecessary comments, blank lines, and name reduction.
-
Image compression
Images are a resource that consumes a lot of traffic on web pages. If losing some color and pixels is not going to affect the user experience too much, compress the image.
At the same time, you can do some cutting and shrinking of the picture to reduce the volume of the picture.
-
-
Choose the correct format for pictures (detailed explanation)
-
PNG
Lossless format, medium compression rate, support transparent background, often used for transparent pictures or ICONS.
-
JPG
Lossy format, good compression rate, commonly used for complex large images, do not support transparent backgrounds.
-
SVG
Vector graphics, programmable. No distortion at all resolutions, but rendering complex graphics consumes performance. Often used for simple graphics.
-
WEBP
Lossless format, better compression than PNG and JPG, and transparent background support. The only downside is poor compatibility. JPG and PNG rollback mechanism can be used in compatible browsers.
-
The server sends an HTTP response
Reduced response time
-
Use the CDN
CDN Content Delivery Network. It relies on the edge servers deployed in various regions to achieve users to obtain content nearby, reduce network congestion, and improve user access speed and hit ratio. Its main key technology is content storage and distribution technology.
Reduce the initial rendering time of the page
-
Server rendering
The biggest benefit of server rendering is optimizing SEO.
At the same time, it can speed up the first screen rendering speed in terms of performance, but this will bring certain pressure to the server, so it needs to be considered comprehensively.
Page rendering (Explain in detail)
To reduce congestion
-
JS blocked
When HTML parsing meets JS, js files will be downloaded and executed first. This is to prevent JS from manipulating DOM and other situations. But we, as operators, can artificially specify which elements can be lazily loaded.
Specify async or defer for the script tag to defer the script.
Async means that JS does not block but executes as soon as the download is complete
Defer will start executing until the download is complete and the entire document has been parsed, and the DOMContentLoaded event is triggered
-
The CSS block
CSS blocks HTML rendering, but in order for the interface to have no style presented to the user, we need to move CSS forward
Reduce rendering times
-
Avoid backflow and redrawing
Backflow, also known as rearrangement, is the process by which information such as the size and position of an element is changed in some way, causing the browser to recalculate and render. Repainting is just changing the style such as background and color etc.
Either way, it costs performance, so we want to avoid loops.
Reduce the number of render nodes
-
Lazy loading
For elements that are not in the user view, we can display them without rendering them until they are in the view.
Lazy loading involves loading and rendering images or DOM elements
Improve rendering efficiency
-
Reduce dom node operations
The browser’s rendering engine is separate from the JS engine. As you can imagine, “cross-boundary communication” between the JS engine and rendering engine is not easy, it is expensive, so we should avoid this operation as much as possible.
-
Leverage event loops and asynchronous updates (explained in detail)