Home  >  Article  >  Web Front-end  >  Focus on the optimization and practice of H5 page opening in seconds

Focus on the optimization and practice of H5 page opening in seconds

藏色散人
藏色散人forward
2023-04-11 15:30:002231browse
This article brings you relevant knowledge about H5. It mainly shares with you the optimization and practice of H5 page opening in seconds. Let’s take a look at it together. I hope it will be helpful to everyone.

Background

In March, we will conduct governance on the instant opening rate of key online H5 projects. This article will gradually introduce how to improve the 1.5 second opening rate through optimization of H5 pages.

Why do we need to optimize?

  • From a user perspective, optimization can make pages load faster, respond more promptly to user operations, and provide a better user experience. It is very important to improve user experience and reduce user churn rate. Among them, the Global Web Performance Matters for ecommerce report also specifically explains the importance of optimization.
  • From an enterprise perspective, optimization can reduce the number of page requests or reduce the bandwidth occupied by requests, which can save considerable resource costs and ultimately increase revenue conversion.

Optimization goal

Focus on the optimization and practice of H5 page opening in seconds

As can be seen from the above picture, some domain names may be lower than 90%, and the highest one does not reach 96%. , there is still a certain gap from the established goal of 98%.

H5 Performance Analysis

Analysis Tools

Webview loads H5

Usually, it is divided into the following stages

  1. Webview initialization.
  2. Arrived at a new page, connected to the network, downloaded html, css, js from the server, and the page had a white screen.
  3. The basic frame of the page appears, js requests page data, and the page is in the loading state.
  4. The required data appears, rendering of the entire page is completed, and the user can interact. Watch the H5 startup process visually from the graphics: Focus on the optimization and practice of H5 page opening in seconds

How to shorten the time of these processes has become the key to optimizing H5 performance. Next, let’s take a detailed look at the optimization points to note at each stage.

Optimization plan

Start from the following aspects:

  • Loading strategy optimization
  • Add skeleton screen
  • Resource request Optimization (static resources, pictures and webp, lazy loading of pictures, on-demand loading of components)
  • Packaging resource optimization
  • CDN & cache

The next step is to analyze them one by one

Loading strategy optimization

Look at a picture first:

developers.google.com/web/fundame…)Focus on the optimization and practice of H5 page opening in secondsFrom this What we can see in the picture can be roughly summarized into the following four points:

  • Default situation: HTML parsing, then loading JS, at this time HTML parsing is interrupted, then JS is executed, and finally JS execution is completed and Resume HTML parsing.
  • defer case: HTML and JS go hand in hand, and JS is executed last (the js script is executed after all elements are loaded, and is executed in the order declared by the js script, but it will not be executed until all the dom documents are parsed) be executed).
  • async case: HTML and JS go hand in hand, and the execution of JS may be completed before HTML is parsed (js scripts are executed out of order, regardless of the order you declare, as long as a certain js script is loaded execute immediately).
  • Module case: similar to the defer case, except that multiple JS files will be loaded during the extraction process (declaring the acript tag type="module" attribute to embrace the module import and export syntax of es6, loading also Similar to defer, except that multiple JS files can be loaded).

Practical examples in the project:

Focus on the optimization and practice of H5 page opening in seconds

Focus on the optimization and practice of H5 page opening in seconds

##Preloading

prefetch and preload

preload is a new web standard that loads resources you specify early in the page life cycle, while ensuring that before the browser's main rendering mechanism starts.

The specific usage is as follows:

    <scirpt></scirpt>
    
    <scirpt></scirpt>复制代码

Focus on the optimization and practice of H5 page opening in seconds

Note: preload is placed next to the title to make it the earliest to intervene.

prefetch 是提示浏览器,用户在下次导航时可能会使用的资源(HTML,JS,CSS或者图片等),因此浏览器为了提升性能可以提前加载、缓存资源。prefetch 的加载优先级相对较低,浏览器在空闲的时候才会在后台加载。用法与 preload 类似,将 rel 的值替换成 prefetch 即可。

preload 是告诉浏览器页面必定需要的资源,浏览器一定会加载这些资源,而 prefetch 是告诉浏览器页面可能需要的资源,浏览器不一定会加载这些资源。所以建议:对于当前页面很有必要的资源使用 preload,对于可能在将来的页面中使用的资源使用 prefetch。

注意:用 preload 和 prefetch 情况下,如果资源不能被缓存,那么都有可能浪费一部分带宽,请慎用。非首页的资源建议不用 preload,prefetch 作为加载下一屏数据来用。

dns-prefetch 和 preconnect

dns-prefetch

DNS 请求需要的带宽非常小,但延迟较高,这点特别是在手机网络上比较明显。预读取 DNS 能让延迟明显减少一些(尤其是移动网络下)。为了帮助浏览器对某些域名进行预解析,你可以在页面的html标签中添加 dns-prefetch 告诉浏览器对指定域名预解析。

dns-prefetch 是一项使浏览器主动去执行域名解析的功能。dns-prefetch 应该尽量的放在网页的前面,推荐放在后面。具体使用方法如下:

<link>复制代码

洗车项目中有体现:

Focus on the optimization and practice of H5 page opening in seconds

注意:dns-prefetch需慎用,推荐首屏加载资源添加DNS Prefetch

preconnect

和 DNS prefetch 类似,preconnect 不仅会解析 DNS,还会建立 TCP 握手连接和 TLS 协议(如果是https的话)。用法如下:

Focus on the optimization and practice of H5 page opening in secondspreconnect 允许浏览器在 HTTP 请求实际发送到服务器之前建立早期连接。可以预先启动 DNS 查找、TCP 握手和 TLS 协商等连接,从而消除这些连接的往返延迟并为用户节省时间。

<link>复制代码

骨架屏

Focus on the optimization and practice of H5 page opening in seconds从图上可以看出有白屏情况,FCP 时间超过了 1秒多,解决下来就用了骨架屏来解决白屏情况 并提升 FCP。

骨架屏就是在页面资源尚未加载完成以及渲染尚未完成时,需要先给用户的展示页面大致结构。直到资源加载完成以及渲染完成后,使用渲染的页面。骨架屏处理方案也很多,常用方案有以下几种:

  • 首屏:可以在index.html模版中手写骨架屏相关代码。
  • 其他页面:可以利用UI提供SVG图
  • 作为SPA中路由切换的loading:需自己编写骨架屏,推荐两个成熟方便定制的svg组件去定制骨架屏-   react-content-loadervue-content-loader
  • 骨架图渲染前不要出现任何网络请求,在此之前 HTML 内容不要超过 4KB。

我这里采用了固定的骨架屏SVG打包自动注入到模板方式。并产出了基于vite 的自动化注入骨架屏和无阻塞缓存资源文件@auto/vite-plugin-cdn私有插件。

举个?:

Focus on the optimization and practice of H5 page opening in secondsFocus on the optimization and practice of H5 page opening in seconds

Resource request optimization

Image compression and webp

Image is the direction that website performance optimization needs to focus on. Why do you say that? Let’s take a look at a picture: Focus on the optimization and practice of H5 page opening in seconds Generally, the cut pictures provided by the UI are uncompressed pictures, so during the development process, we must compress them again. If the compressed image is still larger than 500KB, consider splitting the image into multiple pieces. Currently, there are many image compression methods on the market. I would like to recommend you a useful tool (docsmall). Can batch compress all kinds of pictures.

Focus on the optimization and practice of H5 page opening in seconds

#The advantage of WebP is that it has a better image data compression algorithm, which brings the advantage of smaller image size when the naked eye recognizes no difference in image quality; It has both lossless and lossy compression modes, Alpha transparency and animation features, and the conversion effects on JPEG and PNG are quite excellent, stable and uniform. Image resources are provided internally and can be uploaded to Front-end acceleration service or Front-end static resource serviceThe internal resource library will automatically generate webp format, and format= can be added when processing images when packaging the project. webp is enough. The interface dynamic pictures can be cropped using the @auto/img-crop private package. Webp can also be dynamically supported and the cache time can be set through parameters.

Comparison before and after webp: Focus on the optimization and practice of H5 page opening in secondsFocus on the optimization and practice of H5 page opening in secondsFrom the comparison results, the size of the same image using webp is reduced by at least 50%, and the larger the image, the greater the optimization ratio. The file size is greatly reduced and the loading time is shortened. In scenarios with large page images and a large number of images, the rendering speed of the page is greatly improved.

CDN & Cache

As mentioned above, Front-end acceleration service or Front-end static resource service internal services all integrate CDN functions. For specific circumstances, please refer to the usage documentation.

Applications that combine the above two services can handle resource issues very well. Currently, our new SPA projects are all released to the front-end acceleration service. As shown in the picture: Focus on the optimization and practice of H5 page opening in secondsResource files are automatically cached

Uncovered CDN

From the picture, the left picture does not hit the cache, while the right picture hits the cache. In many projects, because the domain name interface is the same as the web interface, CDN does not enable caching. We will use the domain name Path to enable CDN caching.

Packaging resource optimization

Extracting third-party libraries

Normally, the codes of most third-party libraries will not change without version upgrades. At this time, you can Use DllPlugin: Package third-party libraries with high reusability together, so you don’t need to repackage them if you don’t upgrade.

Advantages of doing this:

  • 提取的第三方库生成的资源版本号(资源的访问连接)不会变,提高了缓存的利用;
  • 避免打包出单个文件的大小太大,不利于加载;
  • 每次构建只重新打包业务代码,提高打包效率。

为了让前端页面性能更优, App WebView 中针对 ReactVueZepto 三大常用框架相关资源及 Polyfill 进行了预加载处理,所以我们把这些固定的资源调整为无阻塞的预加载地址。具体如何使用 App H5提供了 webpack的相关配置说明。

这里针对 vite 的配置做些说明:

import { defineConfig, loadEnv } from &#39;vite&#39;;
import react from &#39;@vitejs/plugin-react&#39;;
import legacy from &#39;@vitejs/plugin-legacy&#39;;
import createExternal from &#39;rollup-plugin-external-globals&#39;;
import cdn from &#39;@auto/vite-plugin-cdn&#39;; 
export default ({ mode }) => {
  process.env = { ...process.env, ...loadEnv(mode, process.cwd()) };
  const { VITE_USER_NODE_ENV = &#39;mock&#39; } = process.env;
  const plugins: Array<any> = [];
  const isProduction = process.env.NODE_ENV === &#39;production&#39;;
  if (isProduction) {
    // 设置预加载的 react 等包为 external
    plugins.push(
      createExternal({
        react: &#39;React&#39;,
        &#39;react-dom&#39;: &#39;ReactDOM&#39;,
        history: &#39;HistoryLibrary&#39;,
        &#39;react-router&#39;: &#39;ReactRouter&#39;,
        &#39;react-router-dom&#39;: &#39;ReactRouterDOM&#39;,
        immer: &#39;immer&#39;,
        axios: &#39;axios&#39;,
        &#39;js-cookie&#39;: &#39;Cookies&#39;,
      }),
    );
    plugins.push(
      cdn({
        enableModule: true,
      }),
    );
  }
  // https://vitejs.dev/config/
  return defineConfig({
      legacy({
        targets: [&#39;> 0.05%&#39;, &#39;not dead&#39;, &#39;not op_mini all&#39;],
      }),
      ...plugins,
    ],

    build: {
      rollupOptions: {
        external: [
          &#39;react&#39;,
          &#39;react-dom&#39;,
          &#39;history&#39;,
          &#39;react-router&#39;,
          &#39;react-router-dom&#39;,
          &#39;axios&#39;,
          &#39;js-cookie&#39;,
        ],
       
      },
    },
  });
};

这里@auto/vite-plugin-cdn私有插件中提供正常骨架屏、预加载资源、处理资源加载顺序

示例:Focus on the optimization and practice of H5 page opening in seconds

Focus on the optimization and practice of H5 page opening in seconds

优化打包资源

我们来看一组图:

从图上看优化前后,文件数从295 个减少到 214 个, 大小从 1.63MB 减少到439.88KB,大小降了73.6460%

webpack 和 vite 配置

设置预警来检验打包文件

资源(asset)是从 webpack 生成的任何文件。此选项根据单个资源体积(单位: bytes),控制 webpack 何时生成 性能提示。 用法:

//  webpack 设置单个静态资源文件的大小最大超过300KB则会给出警告
module.exports = {
  //...
  performance: {
    maxAssetSize: 1024 * 300 
  }
};
// vite 设置
build: {
      chunkSizeWarningLimit: 300 // 块大小警告的限制(以 kbs 为单位)默认 500
    }

将打包后的静态资源控制在 300KB 以内,最终通过 Gzip 压缩后,基本都在 100KB 以内。其他的优化包括提取第三方库、移除调试和无用代码、Tree Shaking 等。

总结

经过以上的一系列的优化实施,我们来看一下优化前后数据的对比:Focus on the optimization and practice of H5 page opening in seconds从2月底开始实施优化,上图可以很明显看出数据的变化,秒开率虽然已经做到了95%以上,达到 98%的只有个别项目,还需要在迭代过程中关注性能以及持续的优化,这里也感谢为H5页面秒开做出贡献的同学。如有什么问题和想法欢迎留言区评论交流。

如果你读完了也不妨点个赞哟,万分感谢!

The above is the detailed content of Focus on the optimization and practice of H5 page opening in seconds. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.im. If there is any infringement, please contact admin@php.cn delete