background

Front-end performance optimization, picture optimization is an essential important link, most of the composition of the web page without picture rendering. Especially in e-commerce projects, there are often a large number of pictures, such as banner advertising picture, menu navigation picture, commodity list picture, etc. The large number of images and the large size of images often affect the page loading speed, resulting in poor user experience.

Optimization scheme

Based on the above problems, the main problem is the number and volume of pictures, so how to improve the speed of loading pictures, improve the user experience. In fact, there are many excellent picture optimization schemes, which can be used for reference. Finally, we carry out overall optimization of the picture in different directions.

Use appropriate image formats

At present, widely used WEB image formats include JPEG/JPG, PNG, GIF, WebP, Base64, SVG, etc., these formats have their own characteristics, and the following is roughly summarized as follows:

Using the right image format usually results in a smaller image size in bytes, which can be reduced without compromising image quality through proper compression.

Reduce network transmission

The small program uses Tencent cloud picture server to provide many picture processing functions, such as picture scaling, picture quality reduction, format conversion, picture cutting, picture rounding and other functions. These functions can be achieved by adding specified parameters in the image URL. The image server will complete the image processing and save it to the CDN server in advance according to the parameter Settings, which greatly reduces the image transmission size.

At present, the image URL returned by the background interface is preprocessed without setting image parameters, such as an 800×800 hd commodity picture with a volume of about 300K, which is easy to lead to slow image loading and rendering, heavy user traffic consumption, and serious impact on user experience. Therefore, we combined the image processing function of Tencent Cloud. Before loading the network image, we detected whether it was the image URL of Tencent cloud domain name. If the domain name matched, we preprocessed the image URL, including adding zooming parameters, adding quality reduction parameters and adding WebP parameters to reduce the image network transmission size

We first look at a picture server is Tencent cloud image processing ability, through the setting of picture scaling/quality reduction /WebP, a size of 800×800, volume 246KB picture, the final output generated 25.6KB, picture volume reduced by 80%, the effect is significant.

zooming

The size of the original image may be larger than the actual size displayed on the client. On the one hand, the image loading is slow, and on the other hand, the user traffic is wasted. If a large image is loaded, the rendering performance will be affected, making users feel sluggish and affecting user experience. Specify the image server to send a smaller image size that better matches the actual display size by adding a zoom parameter.

Image drop mass

Image server support image quality, the value range is 0-100, the default value is the original image quality, reducing the image quality can reduce the size of the image, but too much quality reduction will affect the image display effect, the network default image quality reduction parameter is set to 85, at the same time through the small program: Interfaces wx.getNetworkType, wx.onNetworkStatusChange, and offNetworkStatusChange listen for network status changes to obtain the networkType of the current user, such as the 4G network that the user is currently using. The image quality will be dynamically set to 80. For most services, on the one hand, the image download size can be greatly reduced and the user experience can be guaranteed, on the other hand, the user browsing can be saved. At present, adding the image quality reduction parameter can reduce the image size by at least 30-40%.

/** * set the network status */
const setNetwork = (res: Record<string.any>) = > {
  const { isConnected = true, networkType = 'wifi' } = res;

  this.globalData.isConnected = isConnected;
  this.globalData.networkType = networkType.toLowerCase();
  this.events.emit(EventsEnum.UPDATE_NETWORK, networkType);
};

wx.getNetworkType({ success: (res) = > setNetwork(res) });
wx.offNetworkStatusChange((res) = > setNetwork(res));
wx.onNetworkStatusChange((res) = > setNetwork(res));
Copy the code
/** * Set different quality images according to network environment */
const ImageQuality: Record<string.number> = {
  wifi: 85.'5g': 85.'4g': 80.'3g': 60.'2g': 60};/** * get image quality */
export const getImageQuality = () = > ImageQuality[getApp().globalData.networkType ?? 'wifi'];
Copy the code
Using WebP

Different image formats have their own advantages and disadvantages and use scenarios. WebP image format provides lossy compression and lossless compression. According to Google, WebP lossless images have 26 percent fewer bytes than PNG images, and WebP lossless images have 25-34 percent fewer bytes than similar JPG images. Now the products of major Internet companies have been used, such as Taobao, JINGdong and Meituan.

Here is a WebP sample link (GIF, PNG, JPG to WebP) to intuitively feel the advantages of WebP in picture size.

WebP compatibility on mobile, most users already support Can I use… Support tables for HTML5, CSS3, etc,

For PNG/JPG image format, the WebP parameter is automatically added and converted to WebP image format. Although WebP may take longer to decode than PNG/JPG images, the speed of network transmission is still greatly improved. The current ios 13 system version accounts for a large number of users. The small program obtains the current system version and does not add WebP parameters for degradation processing.

// Check whether webP format is supported
const checkSupportWebp = () = > {
  const { system } = wx.getSystemInfoSync();
  const [platform, version] = system.split(' ');

  if (platform.toLocaleUpperCase() === PlatformEnum.IOS) {
    return Number(version.split('. ') [0]) > IOS_VERSION_13;
  }

  return true; Webp format is supported by default
};
Copy the code

Tip: Because the current picture server does not support, SVG, GIF to WebP, and did not do processing

The optimization effect

Test our small program home list interface loading picture, to compare the effect of optimization before and after

Before optimization Picture number Does not support WebP Support WebP
2300K 10 523K(a 77% reduction in +) 315K (a 86% reduction in +)
248M 100 69M (a 72% reduction in +) 38M (a 84% reduction in +)

After we use Tencent cloud picture server picture processing function, as well as the way of dynamic processing picture format, reduce picture volume, improve picture loading speed, bring the income ratio is very considerable

Lazy loading of images

Lazy loading is a way of performance optimization. Images that do not appear in the visible area of the page are not loaded first and then loaded after scrolling to the visible area, which will greatly improve the page loading performance and improve the user experience.

Realize the principle of

Use applets to provide the Intersection Observer API that listen for whether and what percentage of nodes are visible to the user. This way we can determine if the image element is in the scope and load the image.

Our IntersectionObserver API, based on the applet, encapsulates a monitoring module and exposes IntersectionObserver functions to provide the following usage

import IntersectionObserver from 'utils/observer/observer';

const ob = new IntersectionObserver({
  selector: '.goods-item'.// Specify the target node element to listen on
  observeAll: true.// Whether to observe multiple target nodes simultaneously
  context: this.// Applet this object instance
  delay: 200.// The interval between calling onFinal methods. Default: 200ms
  onEach: ({ dataset }) = > {
    // Every time a listener call is triggered, the onEach method is fired to do some filtering of the data
    const { key } = dataset || {};
    return key;
  },
  onFinal: (data) = > {
    // The onFinal method will be called once after a delay is triggered
    if(! data)return;
    console.log('module view data', data); }});// The built-in function method is as follows:
ob.connect(); // Start listening
ob.disconnect(); // Stop listening
ob.reconnect(); // Reset the listener
Copy the code

Then in our FreeImage image component, add the ability to load images in the visual area. Here is some code

import IntersectionObserver from 'utils/observer';

Component({
  properties: {
    src: String./** * Whether to enable the visual area to load images */
    observer: {
      type: Boolean.value: false,},... },data: {
    isObserver: false. },lifetimes: {
    attached() {
      // Enable visual area to load images
      if (this.data.observer) {
        this.createObserver(); }}},methods: {.../** * listen for images to enter the viewable area */
    createObserver() {
      const ob = new IntersectionObserver({
        selector: '.free-image'.observeAll: true.context: this.onFinal: (data = []) = > {
          data.forEach((item: any) = > {
            this.setData({
              isObserver: true}); ob.disconnect();// Cancel the listener}); }}); ob.connect();// Start listening}}})Copy the code
<free-image observer src="{{ src }}" />
Copy the code

The optimization effect

Test our small program home page list, using pictures lazy loading effect

By using the image lazy loading function, reduce the number of images to load, effectively improve the page loading performance. In the above we have optimized the image volume, so in our small program, only in the case of poor network conditions, will automatically open the image lazy loading function.

Optimize the number of requests

There are a lot of local image resources in our project, such as some icon ICONS, label class cutout, background image, image button, etc. The size of subcontracting of small program is limited: the size of all subcontracting of the whole small program is not more than 20M, and the size of single subcontracting/main package is not more than 2M. Therefore, in order to reduce the volume of small programs, local image resources need to be adjusted, such as image compression and uploading to the CDN server. This can reduce the size of the main package of small programs, and most of the pictures are in Tencent cloud CDN server, although it can accelerate the speed of resource request, when the page needs to download a large number of pictures, it will seriously affect the user experience.

To solve this problem, we need to find a tradeoff point to optimize the number of requests. First, we classify the image resources and use scenarios, and finally determine our plan as follows:

  • Upload large-volume images to the CDN server
  • Use iconFont for monochrome ICONS and use iconfont for colorful ICONSsvgformat
  • Label images, Sprite images are generated and uploaded to the CDN server
  • Image size less than10KB, combined with the use of the scenario, then considerbase64 For example, the volume of a picture is3KBBackground diagram due to appletscss backgroundDoes not support local image import, can be usedbase64 Way to achieve

Other strategies

A larger image detection

Realize the large picture detection mechanism, timely find the problem that the picture does not conform to the specification, when the picture size is too large, do not conform to the size standard of the commodity picture will be reported. In the small program development/experience version, when we set the Debug mode, the picture component FreeImage will automatically detect the large picture, display the current picture size, and set the way of highlighting/flipping the picture to remind the operation students and design students to deal with it

Handling load Failure

If Tencent cloud image processing function is used, the URL preprocessing and transformation may lead to a new URL, which may cause a few abnormal scenarios where images do not exist, leading to loading failure. In case of image loading failure, we still need to reload the original image URL, and then the wrong image URL will be reported to the monitoring platform, which is convenient to adjust the URL preprocessing conversion rules later. At the same time, we also find some wrong image URLS to promote business modification.

This is our image component FreeImage processing image loading failure, the following is part of the code

onError(event: WechatMiniprogram.TouchEvent) {
  const { src, useCosImage } = this.data;

  this.setData({
    loading: false.error: true.lazy: 'error'});// Check whether Tencent cloud service picture
  if (useCosImage) {
    wx.nextTick(() = > {
      // Reload the native image
      this.setData({
        formattedSrc: src, // SRC is the original address
      });
    });
  }

  // Failed to load the image
  app.aegis.report(AegisEnum.IMAGE_LOAD_FAIL, {
    src,
    errMsg: event? .detail.errMsg, });this.triggerEvent('error', event.detail);
}
Copy the code
Check the number of image requests

Use the experience score function of the applet developer tool. Experience score is a function that scores the experience quality of the applet. It will check in real time during the running of the applet, analyze some possible bad experiences, locate the problems, and give some optimization suggestions.

Through the results of experience scoring, we can analyze the existence of too many image requests in a short time, and the existence of too large images with small effective display area. Therefore, according to the results of the analysis, the development needs to control the number of reasonable, can consider using Sprite graphics technology, split domain name or use lazy loading in the off-screen images.

Upload compressed

Before uploading images, reduce file size and compress reasonably while maintaining acceptable resolution. There are a lot of good image compression plug-in tools out there that I won’t cover in detail.

A great image compression site: TinyPNG uses smart lossy compression to reduce the file size of your WebP, PNG and JPEG images