For optimization analysis of Web performance, we should start to discuss from two major aspects, namely: loading optimization and rendering optimization. Of course, we also have other optimization methods, so in Huawei cloud, how do we do performance optimization?

Load optimization

The time analysis process of a complete network request is shown in the figure above:

  • Queuing: Queuing specifies the priority, number of available connections, and disk cache allocation
  • 例 句 : the time spent waiting for a request to be sent
  • DNS Lookup: DNS Lookup time
  • Initial Connection/Connecting: indicates the time used to establish a TCP Connection or retry and negotiate an SSL Connection
  • Request Sent/Sending: Indicates the time used to send a network Request
  • Waiting (TTFB) : number of milliseconds to wait until the initial network request is initiated “until the first byte is received from the server”
  • Content Download/Downloading: Indicates the Downloading time for receiving response data

Based on this, we can make targeted optimization as follows:

1. Optimize network connections

Network connection optimization has three main rules: use CDN to speed up, reduce DNS lookups, and avoid redirects.

  • CDN: A CDN is a collection of geographically distributed Web servers for delivering content more efficiently.
  • DNS lookup: The DNS is used to map host names and IP addresses. The DNS lookup takes 20 to 120 milliseconds.
  • Redirect: Reroute one URL to another. The redirection is done using the 301 and 302 HTTP status codes.

2. Preloading

  • Preload: The browser immediately starts downloading main.js(not blocking the parser) as soon as it encounters the following link tag and puts it in memory, but does not execute the JS statements in it. Preload is used to preload resources required by the current page.
<link rel="preload" href="/main.js" as="script"> 
Copy the code
  • Prefetch: Used to initialize fetching resources for subsequent navigation. Prefetch specifies the lowest resource fetch priority. Prefetch is primarily used to load resources that may be needed for future pages.
<link rel="prefetch" href="/images/big.jpeg"> 
Copy the code
  • Dns-prefetch: Instructs the browser to pre-resolve DNS domain names. This reduces the delay of opening the page. DNS requests are very small in terms of bandwidth, but very high in latency, especially on mobile networks.
<meta http-equiv="x-dns-prefetch-control" content="off">
<link rel="dns-prefetch" href="http://www.spreadfirefox.com/">
Copy the code

3. Load resources using multiple domain names

The number of resources that can be concurrently loaded by a browser under the same domain name is limited. For example, The number of resources that can be concurrently loaded by Internet Explorer 6 and 7 is two, and the number of resources that can be concurrently loaded by Internet Explorer 8 is six. The number of resources that can be concurrently loaded by Chrome varies from version to version. If you can distribute static resources across multiple domains, you can bypass this browser limitation.

4. Reduce HTTP requests

  1. Merging JS files
  2. Merging CSS Files
  3. Using CSS Sprite
  4. Use Base64 to represent simple images

The above four methods, the first two we can use a packaging tool like Webpack to package; For Sprite, there are special tools to make it. Images are encoded in Base64, so for some simple images, such as blank images, you can use Base64 to write directly to HTML.

5. Reduce resource volume

6. Image optimization

  • Eliminate redundant image resources
  • Take advantage of CSS3 effects whenever possible
  • Image cropping
  • Web font icon library
  • Image compression
  • Don’t zoom in

7. Js startup optimization

  • Download only the code the user needs
  • Remove unused code.
  • Load only the resources required by the viewable area (image lazy loading mechanism)
  • Defer to load the JS
  • Webpack dynamic import (route configuration lazy loading)
  • Minimize imported dependencies

Lazy loading

Lazy loading is a method of lazily loading non-critical resources when a page is loaded, but these resources are not loaded until they are needed. In terms of graphics, “non-critical” usually means “off-screen”. The process is as follows :(for the picture lazy loading solution can see my article juejin.cn/post/697794…

  1. Visit a page and start scrolling through the content.
  2. At some point, you scroll the placeholder image into the viewport.
  3. The placeholder image is replaced instantly with the final image.

Monitor window changes to check whether the picture is in the viewable areaExecuted when the target element intersects the device window or other specified element

9. HTTP cache

10. Offline cache

Service Workers essentially act as a proxy server between the Web application and the browser, and can also act as a proxy between the browser and the network when the network is available. With the Service Workers thread, you can hijack connections, orchestrate, and filter responses. It’s a very powerful tool. Therefore, for security reasons, Service workers can only be registered on HTTPS pages.After registering Service workers, it can be used to cache static resources such as CSS, images, fonts, JS and templates:

self.addEventListener('install'.function (event) {
    event.waitUntil(caches.open('mysite-static-v3').then(function (cache) {
        return cache.addAll([
            '/css/whatever-v3.css'.'/css/imgs/sprites-v6.png'.'/css/fonts/whatever-v8.woff'.'/js/all-min-v4.js'
        ]);
    }));
});
Copy the code

11. Using HTTP / 2

Improvements to HTTP2 over HTTP1 include:

  1. multiplexing
  2. Binary framing
  3. The first compression
  4. Server push

Summary of loading optimization

  • Remove unnecessary resources: Compress all resources, remove unused code, and don’t introduce dependencies unless necessary
  • Split code by route: load only the required resources, and lazily load other resources
  • Caching code: Packaging code into different files as often as it changes, so that code is downloaded only after changes are made
  • Keep track of package size: Use tools (webpack-Dashboard, webpack-bundle-Analyzer) to keep track of package size changes and optimize package size in time

Rendering optimization

Let’s take a look at the whole process of page rendering:

1. Optimize JS execution

  • For animation effects, avoid using setTimeout or setInterval and use requestAnimationFrame instead.
  • Move long-running JavaScript from the main thread to the Web Worker.
  • Use microtasks to perform DOM changes to multiple frames.
  • Use Chrome DevTools Timeline and JavaScript profiler to assess the impact of JavaScript.

2. Reduce the scope and complexity of style calculation

The time spent calculating the style of an element is twofold: About 50% of the time is spent matching selectors, and the other half is spent building RenderStyle (computed style representation) from matched rules, adding and removing elements, changing properties, classes, or changing the DOM via animation, all of which cause the browser to recalculate the element style. In many cases, pages or parts of pages are also laid out (that is, automatically rearranged), which is called computation-style computing. So the key to reducing CSS rendering time lies in two things:

  • Reduce the complexity of the selector; Use class-centric methods, such as BEM.
  • Reduce the number of elements whose styles must be computed.

3. Eliminate JavaScript and CSS that block rendering

  1. CSS does not block DOM parsing, but it does block DOM rendering. It needs to be downloaded to the client as soon as possible to reduce the first rendering time.
  2. JS blocks DOM parsing, but the browser “peeks” at the DOM and preloads related resources.
  3. Page rendering is triggered when the browser encounters a script without defer or async attributes, so if the CSS resource has not finished loading before the browser waits for it to finish loading before executing the script.

Other optimization

1. Optimization of API calls

  1. Compact fields that only get the necessary data: specify fields to return when requested
  2. Reduce the number of requests: return after the business processing is completed in the middle station; The center provides bulk processing of requests
  3. Cache data
  4. API query language

2. SSR server rendering — improve home PAGE KPI

3. CSR client rendering

4. Avoid over-optimizing and over-optimizing

  • Don’t waste time doing optimizations that don’t matter
  • Keep your code as simple as possible to improve readability and maintainability