I once read an article about users’ perception of web site performance delays, and it listed several key indicators:
Delay time | Index is introduced |
---|---|
0 ~ 16ms | New frame update time, rendering 60 new frames per second to ensure smooth animation |
0 ~ 100ms | Response user operation time, in this time window the user will feel the response is executed immediately |
100 ~ 1000ms | The time to load a page or update a view is a window in which the user feels the progress of the task is natural and continuous |
>= 1000ms (1s) | Users lose focus on the task they are performing |
>= 10000ms (10s) | Users get frustrated and may abandon the task, and may or may not come back later |
As you can see, performance is important for an application.
In order to have an overall understanding of web application performance optimization, this paper has translated Google’s Web front-end performance optimization guide. The overall performance optimization is divided into three parts: load performance, render performance, and performance evaluation.
1. Loading performance
Loading performance is mainly affected by the user’s network conditions, the number of resources to be loaded, and the size of the resource content. We have no control over the user’s network conditions, so the number of page resources loaded and the size of the resource content is one of the best ways to optimize. On the other hand, we can also make use of the transport protocols we rely on, such as HTTP caching.
1.1 Optimization of resource Loading Performance
Different resource types use slightly different optimizations:
Text resources
Text resources mainly include: HTML, JavaScript, CSS, etc., the main optimization means are:
- Reduce content: minify
- Compress the content: for example, use GZIP compression
- Reduce the use of third-party libraries
- JavaScript specific optimizations
- Tree Shaking
- Code Split
- CSS specific optimizations
- Embed smaller CSS files
- Do not embed large data URIs
- Do not embed CSS properties
Image resources
The main optimization means are as follows:
- Get rid of unnecessary pictures
- Choose the appropriate image format
- PNG: clip art, line painting, need transparency
- Photo JPG:
- : GIF animation
- WebP
- If not sure, save all format comparison sizes at the same time
- Get rid of the metadata
- Resize the picture
- Reasonable size
- Cut the important parts and leave the rest blank
- Reduce image quality: mainly JPG
- Use compression tools such as tinyPNG, which support.png and.jpg
- Use video instead of large GIFs
- Lazy load
1.2 HTTP protocol and cache optimization
Cache has obvious advantages in resource loading optimization. For the same resource, there is no need to do secondary loading when the content is unchanged, which greatly improves the loading efficiency.
Use the CDN
The advantage of CDN is that the resource content is cached in the edge node of CDN through the cache proxy. When the user requests the resource, if the cache is hit, the cached content will be returned directly; otherwise, the user will pull the content back to the source resource server and return it, and cache the resource at the same time
Optimize the HTTP request body
- Merge text content
- Merged images
- Scripts file location: before
- Embedded scripts: when a small amount of code
- Avoid loading the same resource multiple times
- Lazy loading
- Use HTTP/2 features (binary frame layer, request and response multiplexing, data stream priority, one connection per source, flow control, server push, header compression -, security and performance of HPACK)
Use HTTP to cache headers
- Last-modified/if-modified-since: Data from Last requested last-modified; The server returns 200 and the content, indicating that the content has been updated; The server returns 304 no content, indicating that the content has not been updated. Can only be used with GET and HEAD; If-none-match is invalid unless the server does not support if-none-match
- Etag/if-none-match: data from Last request last-modified; The server returns 200 and the content, indicating that the content has been updated; The server returns 304 no content, indicating that the content has not been updated
- cache-control
- No-cache: Cache is allowed, but forces the client to check for updates each time
- No-store: The cache cannot be cached
- Public: Allows browser and intermediate caching
- Private: Allows browser caching but disallows intermediate caching
- Max-age: indicates the maximum cache duration, expressed in seconds. Maximum year: 31536,000
- Expires: Sets the expiration time of a resource; After that point, request new content from the server; An alternative to cache-control; The longest time also cannot exceed one year; If-modified-since, if-unmodified-since, last-modified
1.3 PRPL mode
PRPL is an acronym that describes an interactive mode used to make web pages load and make them faster:
- Push (or preload) : Push or preload the most important resources
- Render: Render the initial path as soon as possible
- Pre-cache: pre-cache the remaining resources
- Lazy load: Lazily loads other routes and non-critical resources
Second, rendering performance
Rendering performance refers to how well a browser can render web content. This performance is mainly influenced by the performance of the user’s device, network conditions, and code logic that affects rendering performance. Again, we have no control over the performance and network conditions of the user’s device, so we can only start with the code logic that affects rendering performance.
2.1 Key Rendering paths of the Browser
The critical rendering path is the set of steps a browser must take to turn HTML, CSS, and JavaScript into a working website. By optimizing the critical render path, we can significantly reduce the time to first render the page.
I won’t go into details here, but if you’re interested, you can go to the resources section at the bottom of the article to find relevant information. This section will focus on optimization.
2.2 Optimization of rendering performance
Optimize JavaScript execution
- RequestAnimationFrame: For animation effects, avoid setTimeout or setInterval and use requestAnimationFrame.
- Reduce complexity or use A Web Worker: Move long-running JavaScript from the main thread to a Web Worker.
- Learn about JavaScript’s “frame tax” : using microtasks to perform DOM changes to multiple frames.
- Avoid micro-optimizing JavaScript: Use Chrome DevTools’ Timeline and JavaScript parser to evaluate the impact of JavaScript.
Narrow the scope and complexity of style calculations
- Reduce the complexity of the selector
- Reduce the number of elements to calculate the style
- Measure the cost of style recalculation
- Write styles using blocks, elements, modifiers (BEM)
Avoid large and complex layouts and layout jitter
- Avoid layout operations where possible: changes to “geometric properties” such as width, height, left side, or top
- Use Flexbox instead of the older layout model
- Avoid forcing synchronous layouts: Always batch read styles first and execute them (the browser can use the layout values from the previous frame), then perform any writes
- Avoid layout jitter: Do not read style values in the loop
Simplify the complexity of rendering and reduce the rendering area
- Trigger layout and draw
- Triggering layout necessarily triggers drawing
- Changing a non-geometric property, such as background, text, or shadow, triggers the draw
- Use Chrome DevTools to quickly identify paint bottlenecks
- Lift elements that move or fade out
- will-change
- Transform: translateZ(0);
- Reduce drawing area: arrange animations and transformations so that they do not overlap too much
- Reduced drawing complexity: Drawing any elements that involve blur (for example, shadows) will take longer than drawing a red box (for example)
Insist on only synthesizer attributes and management counts
- Always use the Transform and opacity property changes to animate
- Elevates the element you intend to animate
- Layer and avoid a surge of layers
- Use Chrome DevTools to understand the layers in your application
Removes jitter from the input handler
- Avoid running input handlers for long periods of time
- Avoid changing styles in the input handler
- Causes the scrolling handler to remove jitter
Third, performance evaluation
Before evaluating the performance of a website, it is important to identify the metrics that measure performance and use them to objectively assess what is going well and what (and how) can be improved.
3.1 Indicator Types
- Perceived load Speed: The speed at which viewing area content is loaded and rendered
- Load Responsiveness: The speed at which referenced JavaScript code is loaded and executed in response to user interaction
- Runtime Responsiveness: How quickly pages respond to user interaction after loading is complete
- Visual Stability: Do elements on the page move in ways that users don’t expect and might interfere with their interactions?
- Smoothness: Are transition and animation render frame rates stable and state changes smooth?
3.2 Important indicators
- First Contentful Paint (FCP): Measures the time it takes from the start of the page to load onto the screen to render any part of the page’s content
- Largest Contentful Paint (LCP): Measures the time it takes from the start of the page to have the Largest block of text or image element rendered on the screen
- First Input Delay (FID): Measures the time between when a user First interacts with your site (that is, when they click a link, click a button, or use a custom JavaScript driven control) and when the browser actually responds to that interaction
- Time to Interactive (TTI): Measures the Time between when the page starts loading and when the visual rendering is done, when the initial script for the page (if any) has been loaded, and can reliably and quickly respond to user input
- Total Blocking Time (TBT): Measures the Total time between the FCP and TTI when the main thread was blocked long enough to prevent an input response
- Cumulative Layout Shift (CLS): Measures the Cumulative score of all unexpected layout transitions that occur between the start of a page loading and the page life cycle state becoming hidden
Iv. Reference Resources
- Techniques to improve website performance
- Load performance optimization
- Critical render path
- Render performance optimization