国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
Optimization plan
Use appropriate image formats
Reduce network transmission
Image scaling
Picture degradation
Using WebP
Optimization effect
圖片懶加載
優(yōu)化效果
優(yōu)化請求數(shù)
其他策略
大圖檢測
加載失敗處理
圖片請求數(shù)檢查
上傳壓縮
Home WeChat Applet Mini Program Development Let's talk in depth about how to optimize images in mini programs

Let's talk in depth about how to optimize images in mini programs

Nov 19, 2021 pm 07:58 PM
Image optimization Applets

This article will share with you a practical application of a small program to see how to optimize images in the small program. I hope it will be helpful to everyone!

Let's talk in depth about how to optimize images in mini programs

Front-end performance optimization and image optimization are indispensable and important links. The rendering of images is indispensable for the composition of most website pages. Especially in e-commerce projects, there are often a large number of pictures, such as banner advertising pictures, menu navigation pictures, product list pictures, etc. Loading a large number of images and excessively large image sizes often affect the page loading speed, resulting in a poor user experience. [Related learning recommendations: 小program development tutorial]

Optimization plan

The main problem based on the above problems is the number of pictures and the size of the pictures, so How to improve image loading speed and improve user experience. In fact, there are many excellent solutions for image optimization, and we can all learn from them. Finally, we optimize the image as a whole in different directions.

Lets talk in depth about how to optimize images in mini programs

Use appropriate image formats

Currently widely used WEB image formats include JPEG/JPG, PNG, GIF, WebP, Base64, SVG, etc., these formats have their own characteristics. The following is a brief summary:

Lets talk in depth about how to optimize images in mini programs

Using appropriate image formats can usually lead to smaller image byte sizes , through a reasonable compression rate, the image size can be reduced without affecting the image quality.

Reduce network transmission

The applet uses Tencent Cloud Image Server, which provides many image processing functions, such as image scaling, image reduction Quality, format conversion, image cropping, image rounding and other functions. These functions can be achieved by adding specified parameters to the image URL. The image server will process the image in advance according to the parameter settings and save it to the CDN server, which greatly reduces image transmission. size.

Currently, the image URLs returned by the background interface are all without setting the image parameter preprocessing. For example, a 800x800 size high-definition product image has a volume of about 300k. , which can easily lead to slow image loading and rendering, high user traffic consumption, and seriously affects the user experience. Therefore, we combine the image processing function of Tencent Cloud. Before loading the network image, we first detect whether it is the image URL of the Tencent Cloud domain name. If the domain name matches, the image URLPerform preprocessing, which includes Add scaling parameters, Add degradation parameters,Add WebP parameters to reduce image network transmission size

Let's first look at a picture that passes through the picture server and uses Tencent Cloud's picture processing capabilities. By setting the picture scaling/degradation/WebP, a picture with a size of 800x800 and a volume of 246KB is finally output and generated. 25.6KB, the image size is reduced by 80%, the effect is remarkable.

Lets talk in depth about how to optimize images in mini programs

Image scaling

Currently, the business background uploads original images, and the original image size may be larger than the actual size displayed on the client. Large size will lead to slow image loading on the one hand, and waste of user traffic on the other. If a large-sized image is loaded, it will also affect the rendering performance, making the user feel stuck and affecting the user experience. By adding a scaling parameter, specify the image server to deliver an image size that is smaller and more consistent with the actual display size.

Picture degradation

The picture server supports picture quality, the value range is 0-100, the default value is the original picture quality, by reducing the picture Quality can reduce the image size, but too much quality reduction will also affect the display effect of the image. The network default image quality reduction parameter is set to 85, which is also provided through the mini program: wx.getNetworkType, wx.onNetworkStatusChange, offNetworkStatusChange interfaces monitor network status changes to obtain the current user's network type networkType, such as the 4G# currently used by the user ## network, the image quality will be dynamically set to 80. For most business situations, on the one hand, it can greatly reduce the image download size and ensure user experience, on the other hand, it saves users browsing. Currently, adding images reduces the Quality parameters can reduce the image size by at least 30-40%.

/**
 * 設(shè)置網(wǎng)絡(luò)情況
 */
const setNetwork = (res: Record<string, any>) => {
  const { isConnected = true, networkType = &#39;wifi&#39; } = 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));
/**
 * 根據(jù)網(wǎng)絡(luò)環(huán)境設(shè)置不同質(zhì)量圖片
 */
const ImageQuality: Record<string, number> = {
  wifi: 85,
  &#39;5g&#39;: 85,
  &#39;4g&#39;: 80,
  &#39;3g&#39;: 60,
  &#39;2g&#39;: 60,
};

/**
 * 獲取圖片質(zhì)量
 */
export const getImageQuality = () => ImageQuality[getApp().globalData.networkType ?? &#39;wifi&#39;];
Using WebP

As mentioned above, different image formats have their own advantages, disadvantages and usage scenarios. Among them, WebP image format provides lossy compression and Lossless compressed image format. According to official data from Google, compared with PNG, the number of bytes of WebPlossless images is 26%, WebPlossy images have 25-34% fewer bytes than similar JPGimages. Nowadays, the products of major Internet companies have been used, such as Taobao, JD.com, and Meituan.

Put a WebP example link here (GIF, PNG, JPG to Webp), and intuitively feel the advantages of WebP in image size.

Lets talk in depth about how to optimize images in mini programs

In the compatibility of WebP on the mobile terminal, most users have already supported itCan I use... Support tables for HTML5, CSS3, etc,

Lets talk in depth about how to optimize images in mini programs

automatically adds WebP# for the png/jpg image format. ## Parameters, converted to WebP image format. Although WebP may take longer to decode than png/jpg, the relative network transmission speed is still greatly improved. Currently, the ios 13 system version has a large proportion of users. The applet obtains the current system version and does not add WebP parameters for downgrade processing.

// 檢查是否支持webp格式
const checkSupportWebp = () => {
  const { system } = wx.getSystemInfoSync();
  const [platform, version] = system.split(&#39; &#39;);

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

  return true; // 默認(rèn)支持webp格式
};

Tips: Since the current image server does not support

SVG, GIF conversion to WebP, no processing is done

Optimization effect

Test the loading image of the list interface on the home page of our mini program to compare the effect before and after optimization

Before optimizationNumber of picturesDoes not support WebPSupports WebP##2300K (77% reduction)(86% reduction)248M(Reduced by 72%)(Reduced by 84%)

Lets talk in depth about how to optimize images in mini programs

經(jīng)過我們通過使用騰訊云圖片服務(wù)器的圖片處理功能,以及動態(tài)處理圖片格式的方式,減少圖片體積,提高圖片加載速度,帶來的收益比非??捎^的

圖片懶加載

懶加載是一種性能優(yōu)化的方式,將頁面內(nèi)未出現(xiàn)在可視區(qū)域內(nèi)的圖片先不做加載, 等到滾動到可視區(qū)域后再去加載,對于頁面加載性能上會有很大的提升,也提高了用戶體驗(yàn)。

實(shí)現(xiàn)原理

使用小程序提供Intersection Observer API,監(jiān)聽某些節(jié)點(diǎn)是否可以被用戶看見、有多大比例可以被用戶看見。這樣我們就能判斷圖片元素是否在可是范圍中,進(jìn)行圖片加載。

我們基于小程序的Intersection Observer API,封裝一個監(jiān)聽模塊曝光 IntersectionObserver函數(shù)工具,提供以下用法

import IntersectionObserver from &#39;utils/observer/observer&#39;;

const ob = new IntersectionObserver({
  selector: &#39;.goods-item&#39;, // 指定監(jiān)聽的目標(biāo)節(jié)點(diǎn)元素
  observeAll: true, // 是否同時(shí)觀測多個目標(biāo)節(jié)點(diǎn)
  context: this, // 小程序 this 對象實(shí)例
  delay: 200, // 調(diào)用 onFinal 方法的間隔時(shí)間,默認(rèn) 200ms
  onEach: ({ dataset }) => {
    // 每一次觸發(fā)監(jiān)聽調(diào)用時(shí),觸發(fā) onEach 方法,可以對數(shù)據(jù)進(jìn)行一些過濾處理
    const { key } = dataset || {};
    return key;
  },
  onFinal: (data) => {
    // 在觸發(fā)監(jiān)聽調(diào)用一段時(shí)間 delay 后,會調(diào)用一次 onFinal 方法,可以進(jìn)行埋點(diǎn)上報(bào)
    if (!data) return;
    console.log(&#39;module view data&#39;, data);
  },
});

// 內(nèi)置函數(shù)方法,如下:
ob.connect(); // 開始監(jiān)聽
ob.disconnect(); // 停止監(jiān)聽
ob.reconnect(); // 重置監(jiān)聽

然后在我們的FreeImage圖片組件,添加可視區(qū)域加載圖片的功能,以下是部分代碼

import IntersectionObserver from &#39;utils/observer&#39;;

Component({
  properties: {
    src: String,
    /**
     * 是否開啟可視區(qū)域加載圖片
     */
    observer: {
      type: Boolean,
      value: false,
    },
    ....
  },

  data: {
    isObserver: false,
    ...
  },

  lifetimes: {
    attached() {
      // 開啟可視區(qū)域加載圖片
      if (this.data.observer) {
        this.createObserver();
      }
    },
  },
  methods: {
    ...

    /**
     * 監(jiān)聽圖片是否進(jìn)入可視區(qū)域
     */
    createObserver() {
      const ob = new IntersectionObserver({
        selector: &#39;.free-image&#39;,
        observeAll: true,
        context: this,
        onFinal: (data = []) => {
          data.forEach((item: any) => {
            this.setData({
              isObserver: true,
            });
            ob.disconnect(); // 取消監(jiān)聽
          });
        },
      });

      ob.connect(); // 開始監(jiān)聽
    }
  }
})
<free-image observer  />

優(yōu)化效果

測試我們小程序首頁列表,使用圖片懶加載的效果

Lets talk in depth about how to optimize images in mini programs

通過使用圖片懶加載的功能,減少圖片數(shù)量的加載,有效提高頁面加載性能。在上述我們已經(jīng)對圖片體積進(jìn)行優(yōu)化過,所以在我們小程序中,只有在網(wǎng)絡(luò)情況較差的情況下,才會自動開啟圖片懶加載功能。

優(yōu)化請求數(shù)

我們項(xiàng)目中有很多本地圖片資源,比如一些 icon 圖標(biāo)、標(biāo)簽類切圖、背景圖、圖片按鈕等。而小程序分包大小是有限制:整個小程序所有分包大小不超過 20M,而單個分包/主包大小不能超過 2M。所以為了減輕小程序體積,本地圖片資源需要進(jìn)行調(diào)整,比如圖片壓縮、上傳到 CDN 服務(wù)器。這樣能減少了小程序主包大小,而大部分圖片都在騰訊云 CDN 服務(wù)器中,雖然可以加速資源的請求速度,當(dāng)頁面打開需要同時(shí)下載大量的圖片的話,就會嚴(yán)重影響了用戶的使用體驗(yàn)。

針對此問題,需要找到權(quán)衡點(diǎn)來實(shí)現(xiàn)來優(yōu)化請求數(shù),首先我們把圖片資源進(jìn)行分類,以及使用場景,最后確定我們方案如下:

  • 較大體積的圖片,選擇上傳到 CDN 服務(wù)器
  • 單色圖標(biāo)使用 iconfont 字體圖標(biāo),多彩圖標(biāo)則使用svg格式
  • 標(biāo)簽類的圖片,則生成雪碧圖之后上傳到 CDN 服務(wù)器
  • 圖片體積小于10KB,結(jié)合使用場景,則考慮base64 ,比如一張圖片體積為3KB的背景圖,由于小程序css background不支持本地圖片引入,可以使用 base64 方式實(shí)現(xiàn)

其他策略

大圖檢測

實(shí)現(xiàn)大圖檢測機(jī)制,及時(shí)發(fā)現(xiàn)圖片不符合規(guī)范的問題,當(dāng)發(fā)現(xiàn)圖片尺寸太大,不符合商品圖尺寸標(biāo)準(zhǔn)時(shí)會進(jìn)行上報(bào)。在小程序開發(fā)版/體驗(yàn)版中,當(dāng)我們設(shè)置開啟Debug模式,圖片組件FreeImage會自動檢測到大圖片時(shí),顯示當(dāng)前圖片尺寸、以及設(shè)置圖片高亮/翻轉(zhuǎn)的方式提醒運(yùn)營同學(xué)和設(shè)計(jì)同學(xué)進(jìn)行處理

Lets talk in depth about how to optimize images in mini programs

加載失敗處理

使用騰訊云圖片處理功能,URL預(yù)處理轉(zhuǎn)換后得新 URL,可能會存在少量圖片不存在的異常場景導(dǎo)致加載失敗。遇到圖片加載失敗時(shí),我們還是需要重新加載原始圖片 URL, 之后會將錯誤圖片 URL 上報(bào)到監(jiān)控平臺,方便之后調(diào)整 URL 預(yù)處理轉(zhuǎn)換規(guī)則,同時(shí)也發(fā)現(xiàn)一部分錯誤的圖片 URL 推動業(yè)務(wù)修改。

這是我們圖片組件FreeImage 處理圖片加載失敗,以下是部分代碼

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

  this.setData({
    loading: false,
    error: true,
    lazy: &#39;error&#39;,
  });

  // 判斷是否騰訊云服務(wù)的圖片
  if (useCosImage) {
    wx.nextTick(() => {
      // 重新加載原生圖片
      this.setData({
        formattedSrc: src, // src 是原圖地址
      });
    });
  }

  // 上報(bào)圖片加載失敗
  app.aegis.report(AegisEnum.IMAGE_LOAD_FAIL, {
    src,
    errMsg: event?.detail.errMsg,
  });

  this.triggerEvent(&#39;error&#39;, event.detail);
}

圖片請求數(shù)檢查

使用小程序開發(fā)者工具的體驗(yàn)評分功能,體驗(yàn)評分是一項(xiàng)給小程序的體驗(yàn)好壞打分的功能,它會在小程序運(yùn)行過程中實(shí)時(shí)檢查,分析出一些可能導(dǎo)致體驗(yàn)不好的地方,并且定位出哪里有問題,以及給出一些優(yōu)化建議。

Lets talk in depth about how to optimize images in mini programs

通過體驗(yàn)評分的結(jié)果,可以分析我們存在短時(shí)間內(nèi)發(fā)起太多的圖片請求,以及存在圖片太大而有效顯示區(qū)域較小。所以根據(jù)分析的結(jié)果,開發(fā)需要合理控制數(shù)量,可考慮使用雪碧圖技術(shù)、拆分域名或在屏幕外的圖片使用懶加載等。

上傳壓縮

圖片在上傳前在保持可接受的清晰度范圍內(nèi)同時(shí)減少文件大小,進(jìn)行合理壓縮?,F(xiàn)如今有很多不錯的圖片壓縮插件工具,就不在詳情介紹了。

推薦一個比較優(yōu)秀的圖片壓縮網(wǎng)站:TinyPNG使用智能有損壓縮技術(shù)將您的 WebP, PNG and JPEG 圖片的文件大小降低

更多編程相關(guān)知識,請?jiān)L問:編程入門??!

The above is the detailed content of Let's talk in depth about how to optimize images in mini programs. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Develop WeChat applet using Python Develop WeChat applet using Python Jun 17, 2023 pm 06:34 PM

With the popularity of mobile Internet technology and smartphones, WeChat has become an indispensable application in people's lives. WeChat mini programs allow people to directly use mini programs to solve some simple needs without downloading and installing applications. This article will introduce how to use Python to develop WeChat applet. 1. Preparation Before using Python to develop WeChat applet, you need to install the relevant Python library. It is recommended to use the two libraries wxpy and itchat here. wxpy is a WeChat machine

Implement card flipping effects in WeChat mini programs Implement card flipping effects in WeChat mini programs Nov 21, 2023 am 10:55 AM

Implementing card flipping effects in WeChat mini programs In WeChat mini programs, implementing card flipping effects is a common animation effect that can improve user experience and the attractiveness of interface interactions. The following will introduce in detail how to implement the special effect of card flipping in the WeChat applet and provide relevant code examples. First, you need to define two card elements in the page layout file of the mini program, one for displaying the front content and one for displaying the back content. The specific sample code is as follows: &lt;!--index.wxml--&gt;&l

Alipay launched the 'Chinese Character Picking-Rare Characters' mini program to collect and supplement the rare character library Alipay launched the 'Chinese Character Picking-Rare Characters' mini program to collect and supplement the rare character library Oct 31, 2023 pm 09:25 PM

According to news from this site on October 31, on May 27 this year, Ant Group announced the launch of the "Chinese Character Picking Project", and recently ushered in new progress: Alipay launched the "Chinese Character Picking-Uncommon Characters" mini program to collect collections from the society Rare characters supplement the rare character library and provide different input experiences for rare characters to help improve the rare character input method in Alipay. Currently, users can enter the "Uncommon Characters" applet by searching for keywords such as "Chinese character pick-up" and "rare characters". In the mini program, users can submit pictures of rare characters that have not been recognized and entered by the system. After confirmation, Alipay engineers will make additional entries into the font library. This website noticed that users can also experience the latest word-splitting input method in the mini program. This input method is designed for rare words with unclear pronunciation. User dismantling

Can small programs use react? Can small programs use react? Dec 29, 2022 am 11:06 AM

Mini programs can use react. How to use it: 1. Implement a renderer based on "react-reconciler" and generate a DSL; 2. Create a mini program component to parse and render DSL; 3. Install npm and execute the developer Build npm in the tool; 4. Introduce the package into your own page, and then use the API to complete the development.

How uniapp achieves rapid conversion between mini programs and H5 How uniapp achieves rapid conversion between mini programs and H5 Oct 20, 2023 pm 02:12 PM

How uniapp can achieve rapid conversion between mini programs and H5 requires specific code examples. In recent years, with the development of the mobile Internet and the popularity of smartphones, mini programs and H5 have become indispensable application forms. As a cross-platform development framework, uniapp can quickly realize the conversion between small programs and H5 based on a set of codes, greatly improving development efficiency. This article will introduce how uniapp can achieve rapid conversion between mini programs and H5, and give specific code examples. 1. Introduction to uniapp unia

Teach you how to use public account template messages in mini programs (with detailed ideas) Teach you how to use public account template messages in mini programs (with detailed ideas) Nov 04, 2022 pm 04:53 PM

This article brings you some related issues about WeChat mini programs. It mainly introduces how to use official account template messages in mini programs. Let’s take a look at them together. I hope it will be helpful to everyone.

Tutorial on writing a simple chat program in Python Tutorial on writing a simple chat program in Python May 08, 2023 pm 06:37 PM

Implementation idea: Establishing the server side of thread, so as to process the various functions of the chat room. The establishment of the x02 client is much simpler than the server. The function of the client is only to send and receive messages, and to enter specific characters according to specific rules. To achieve the use of different functions, therefore, on the client side, you only need to use two threads, one is dedicated to receiving messages, and the other is dedicated to sending messages. As for why not use one, that is because, only

Geographical positioning and map display using PHP and mini-programs Geographical positioning and map display using PHP and mini-programs Jul 04, 2023 pm 04:01 PM

Geolocation positioning and map display of PHP and mini programs Geolocation positioning and map display have become one of the necessary functions in modern technology. With the popularity of mobile devices, people's demand for positioning and map display is also increasing. During the development process, PHP and applets are two common technology choices. This article will introduce you to the implementation method of geographical location positioning and map display in PHP and mini programs, and attach corresponding code examples. 1. Geolocation in PHP In PHP, we can use third-party geolocation

See all articles

    10523K315K
    10069M 38M

          <rt id="sfz4q"><delect id="sfz4q"></delect></rt>