5
头图

Loading Speed Optimization Special > Volume Optimization Sharing

What can we think of when it comes to loading speed optimization? What can be found online? CDN? GZIP? Enable caching? HTTP2? Tree-shaking?

Are these correct? is not all ! Next, we analyze it in detail.

Network, loading speed optimization

  1. Why do I say that CDN can speed up is not entirely correct? Talking about toxicity without the dose is a
    What does CDN mean?

    The full name of CDN is Content Delivery Network, that is, Content Delivery Network. CDN is an intelligent virtual network built on the basis of the existing network, relying on edge servers deployed in various places, through the load balancing, content distribution, scheduling and other functional modules of the central platform, enables users to obtain the desired content nearby , reducing network Congestion, improve user access response speed and hit rate. The key technologies of CDN mainly include content storage and distribution technology.
    1. If your CDN itself has fewer nodes and is not fully covered, it will not speed up. (For example, the CDN you bought has no overseas nodes, but you want to improve the access speed of overseas nodes)
    2. If your CDN is on the external network and your project is on the internal network, the speed will be slower. (The distance of the intranet is relatively close, so the speed is fast, and the bandwidth of the intranet is sufficient, so the speed is fast)
    3. Can your CDN handle your request magnitude? (For example, major manufacturers are currently developing their own cloud services, Alibaba Cloud, Tencent Cloud)
  2. Does turning on GZIP really speed up it? Yes it's really speeding up. But generally the server is already turned on.
    Is there no loss? Lossy gzip is calculated for each file, and there is no cache. The corresponding gz file can be generated manually.
  3. enable cache? Brainless cache? It seems that you are not dominated by ios.
    Generally speaking, the cache is also turned on. Our current general solution is that html files are not cached, and js and css are strongly cached for hash control.
  4. Is HTTP2 really a lifesaver? In general, yes, it supports multiplexing (break through the limit of six links, such as slow interfaces, large files), and header compression.
    But in the case of high latency, HTTP2 will be slower
  5. Wired vs wireless (WIFI, 4G), does the service provider have an impact on the network? Are only external network projects affected?

    1. Extranet. The service provider has an impact on the network. For example, my home is mobile, and the ping part of the ip has serious packet loss, and the same is true for optical fiber and 4G. There is no problem with using Unicom 4G.
    2. intranet. Wired is recommended here, which is relatively stable. There are two scenarios here:

      1. Companies, generally AP panels. But sometimes AP nodes just can't be replaced, and occasionally the network fluctuates. When looking at the data of the P90, it is particularly ugly.
      2. At home, there is usually a single router. You can compare the loading speed when the signal is strong and when the signal is weak.

volume optimization

  1. Tree-shaking. It seems that with Tree-shaking, everything is fine.

    1. But it is enabled by default after webpack4. ( yarn serve is not optimized, yarn build is optimized, internally controlled by environment variables)
    2. Tree-shaking only works for ES Module, not for commonjs, nor for umd.
    3. If your tripartite package doesn't support it, then it doesn't support it. So here you need to update the version of your package to support on-demand and tree-shaking
  2. Dependency sharing.

    1. For example, we wrote a Request library, which uses axios. Then we have a message center library, which also uses axios. At this time, there will be two axios in the output package.
      Here we use (monorepo Lerna yarn) + (config.externals) to achieve dependency sharing and only load one copy of axios.
    2. There is also a case where we use the On Demand Component library. However, the main project is not imported on demand, but imported in full, resulting in element-ui being loaded twice. The solution is to change the main project to full on-demand.

      [
       'component',
       {
       "libraryName": "element-ui",
       "styleLibraryName": "theme-chalk"
       },
       'element-ui',
      ],
  3. subcontract. Delay loading and asynchronous loading of unnecessary resources. For example, there is a process center that loads thousands of processes synchronously when you approve it. But you only need to use one of them.

    1. Vue components support asynchronous loading. Load it when the component actually renders.

      Vue.component('async-example', function (resolve, reject) {
          setTimeout(function () {
              // 向 `resolve` 回调传递组件定义
              resolve({
                  template: '<div>I am async!</div>'
              })
          }, 1000)
      })
      Vue.component(
          'async-webpack-example',
          // 这个动态导入会返回一个 `Promise` 对象。
          () => import('./my-async-component')
      )
    2. It can also be loaded asynchronously for large dependencies (xlsx.js, echarts) or other resources that are not in a hurry

      injectFn() {
          if (this.injected) {return;}
          this.injected = true;
          if (this.useBuiltIn && this.username && this.Prop) {
              import('../../../inject.js').then(({ inject }) => {
                  inject(this.Prop!, this.username);
              });
          }
      }
    3. Co-package. It can't be disassembled too finely, and the QPS has been improved for nothing.

      1. What is compression? To put it bluntly, it is the same and merged, for example, '11111111111111111111' is changed to '1'.repeat(20)

        Content compression is as simple as removing excess whitespace, inserting single repeating characters to indicate repeated characters in a string, and replacing small bit strings with frequently used characters. This type of compression can reduce the size of text files by 50%. Compression is performed by programs using specific formulas and algorithms that determine how to compress and decompress data.
        gzip uses the deflate algorithm for compression. gzip For the file to be compressed, first use a variant of the LZ77 algorithm to compress, and then use the Huffman encoding method for the result obtained
  4. Reasonable babel handling. For example, for your intranet project, you can only support browsers of higher versions, reducing babel and polyfill.

    # 你知道这代表了什么?
    > 1%
    last 2 versions # 表示将会支持 IE10 & IE11

Logic optimization

Reduce serial code.

  1. Promise.all instead of axios().then(() => axios())
  2. axios1 = axios();axios2 = axios();await Promise.all(axios1,axios2); instead of await axios();await axios();

Summarize

The road of optimization complements each other.

  1. Optimize the network to load faster and execute faster.
  2. Optimized concurrency without blocking, parallel loading, and faster execution.
  3. Optimized size, smaller size, higher multiplexing, so that less bandwidth can be used, and the same can be executed faster
  4. Use cache, lower QPS, and do DNS resolution in advance. It can also make loading faster.

Project combat

I provided some minimal cases in the repository: Demo repository address , you just need to look at the example to see the problem directly (and then you can optimize it).

For example:
image.png

Analysis method

Chrome DevTools Lighthouse

Here we can rate our page, will also give optimization suggestions . If you can optimize the points here, then your page load will take off.

  1. Let's take a look at the Sifu homepage, and the score is quite high. However, it will definitely be much better if they are static and straight out. Generally, the slow ones are Vue, react, single-page application, and boulder application in the background.
    image.png
  2. Let's take a look at the Nuggets homepage again. This score is almost a problem. We can see that there are some optimization suggestions. It seems that their homepage data seems to be a skeleton, and then the data that comes back later.
    image.png
  3. I heard about 26 points before, I'll take a look too. image.png

Chrome DevTools Network

This is mainly to see the network blocking situation, for example, when http1.1 is the request blocking you.

yarn build --report

This is mainly to analyze the package volume, and the tools I use are mainly this.

For example, in this case, you can see that there are multiple axios, and where each axios is introduced. At this time, you can consider using peerDependencies or externals to deal with such resources.

image.png

Chrome DevTools Performance

This is mainly to analyze the efficiency of code execution.


linong
29.2k 声望9.5k 粉丝

Read-Search-Ask