Home>Article>WeChat Applet> Let’s talk in depth about how to optimize images in mini programs
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!
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]
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.
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:
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.
The applet usesTencent Cloud Image Server, which provides many image processing functions, such asimage scaling, image reduction Quality, format conversion, image cropping, image rounding
and other functions. These functions can be achieved by adding specified parameters to the imageURL
. The image server will process the image in advance according to the parameter settings and save it to theCDN
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, a800x800
size high-definition product image has a volume of about300k
. , 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 imageURL
of the Tencent Cloud domain name. If thedomain name
matches, the imageURL
Perform preprocessing, which includesAdd 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 of800x800
and a volume of246KB
is finally output and generated.25.6KB
, the image size is reduced by80%
, the effect is remarkable.
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 displaysize
.
The picture server supports picture quality, the value range is0-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 to85
, 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 typenetworkType
, such as the4G# 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%.
/** * 设置网络情况 */ const setNetwork = (res: Record) => { 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));
/** * 根据网络环境设置不同质量图片 */ const ImageQuality: Record= { wifi: 85, '5g': 85, '4g': 80, '3g': 60, '2g': 60, }; /** * 获取图片质量 */ export const getImageQuality = () => ImageQuality[getApp().globalData.networkType ?? 'wifi'];
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 fromGoogle
, compared withPNG
, the number of bytes ofWebP
lossless images is26%
,WebP
lossy images have25-34%
fewer bytes than similarJPG
images. Nowadays, the products of major Internet companies have been used, such as Taobao, JD.com, and Meituan.
Put aWebP example link here (GIF, PNG, JPG to Webp), and intuitively feel the advantages ofWebP
in image size.
In the compatibility ofWebP
on the mobile terminal, most users have already supported itCan I use... Support tables for HTML5, CSS3, etc,
automatically addsWebP# for the
png/
jpgimage format. ## Parameters, converted to
WebPimage format. Although
WebPmay take longer to decode than
png/
jpg, the relative network transmission speed is still greatly improved. Currently, the
ios 13system version has a large proportion of users. The applet obtains the current system version and does not add
WebPparameters for downgrade processing.
// 检查是否支持webp格式 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格式 };
Tips: Since the current image server does not supportSVG, GIF
conversion to
WebP, no processing is done
经过我们通过使用腾讯云图片服务器的图片处理功能,以及动态处理图片格式的方式,减少图片体积,提高图片加载速度,带来的收益比非常可观的
懒加载是一种性能优化的方式,将页面内未出现在可视区域内的图片先不做加载, 等到滚动到可视区域后再去加载,对于页面加载性能上会有很大的提升,也提高了用户体验。
实现原理
使用小程序提供Intersection Observer API
,监听某些节点是否可以被用户看见、有多大比例可以被用户看见。这样我们就能判断图片元素是否在可是范围中,进行图片加载。
我们基于小程序的Intersection Observer API
,封装一个监听模块曝光IntersectionObserver
函数工具,提供以下用法
import IntersectionObserver from 'utils/observer/observer'; const ob = new IntersectionObserver({ selector: '.goods-item', // 指定监听的目标节点元素 observeAll: true, // 是否同时观测多个目标节点 context: this, // 小程序 this 对象实例 delay: 200, // 调用 onFinal 方法的间隔时间,默认 200ms onEach: ({ dataset }) => { // 每一次触发监听调用时,触发 onEach 方法,可以对数据进行一些过滤处理 const { key } = dataset || {}; return key; }, onFinal: (data) => { // 在触发监听调用一段时间 delay 后,会调用一次 onFinal 方法,可以进行埋点上报 if (!data) return; console.log('module view data', data); }, }); // 内置函数方法,如下: ob.connect(); // 开始监听 ob.disconnect(); // 停止监听 ob.reconnect(); // 重置监听
然后在我们的FreeImage
图片组件,添加可视区域加载图片的功能,以下是部分代码
import IntersectionObserver from 'utils/observer'; Component({ properties: { src: String, /** * 是否开启可视区域加载图片 */ observer: { type: Boolean, value: false, }, .... }, data: { isObserver: false, ... }, lifetimes: { attached() { // 开启可视区域加载图片 if (this.data.observer) { this.createObserver(); } }, }, methods: { ... /** * 监听图片是否进入可视区域 */ createObserver() { const ob = new IntersectionObserver({ selector: '.free-image', observeAll: true, context: this, onFinal: (data = []) => { data.forEach((item: any) => { this.setData({ isObserver: true, }); ob.disconnect(); // 取消监听 }); }, }); ob.connect(); // 开始监听 } } })
测试我们小程序首页列表,使用图片懒加载的效果
通过使用图片懒加载的功能,减少图片数量的加载,有效提高页面加载性能。在上述我们已经对图片体积进行优化过,所以在我们小程序中,只有在网络情况较差的情况下,才会自动开启图片懒加载功能。
我们项目中有很多本地图片资源,比如一些 icon 图标、标签类切图、背景图、图片按钮等。而小程序分包大小是有限制:整个小程序所有分包大小不超过20M
,而单个分包/主包大小不能超过2M
。所以为了减轻小程序体积,本地图片资源需要进行调整,比如图片压缩、上传到 CDN 服务器。这样能减少了小程序主包大小,而大部分图片都在腾讯云 CDN 服务器中,虽然可以加速资源的请求速度,当页面打开需要同时下载大量的图片的话,就会严重影响了用户的使用体验。
针对此问题,需要找到权衡点来实现来优化请求数,首先我们把图片资源进行分类,以及使用场景,最后确定我们方案如下:
svg
格式10KB
,结合使用场景,则考虑base64
,比如一张图片体积为3KB
的背景图,由于小程序css background
不支持本地图片引入,可以使用base64
方式实现实现大图检测机制,及时发现图片不符合规范的问题,当发现图片尺寸太大,不符合商品图尺寸标准时会进行上报。在小程序开发版/体验版中,当我们设置开启Debug
模式,图片组件FreeImage
会自动检测到大图片时,显示当前图片尺寸、以及设置图片高亮/翻转
的方式提醒运营同学和设计同学进行处理
使用腾讯云图片处理功能,URL
预处理转换后得新 URL,可能会存在少量图片不存在的异常场景导致加载失败
。遇到图片加载失败时,我们还是需要重新加载原始图片 URL, 之后会将错误图片 URL 上报到监控平台,方便之后调整 URL 预处理转换规则,同时也发现一部分错误的图片 URL 推动业务修改。
这是我们图片组件FreeImage
处理图片加载失败,以下是部分代码
onError(event: WechatMiniprogram.TouchEvent) { const { src, useCosImage } = this.data; this.setData({ loading: false, error: true, lazy: 'error', }); // 判断是否腾讯云服务的图片 if (useCosImage) { wx.nextTick(() => { // 重新加载原生图片 this.setData({ formattedSrc: src, // src 是原图地址 }); }); } // 上报图片加载失败 app.aegis.report(AegisEnum.IMAGE_LOAD_FAIL, { src, errMsg: event?.detail.errMsg, }); this.triggerEvent('error', event.detail); }
使用小程序开发者工具的体验评分功能,体验评分是一项给小程序的体验好坏打分的功能,它会在小程序运行过程中实时检查,分析出一些可能导致体验不好的地方,并且定位出哪里有问题,以及给出一些优化建议。
通过体验评分的结果,可以分析我们存在短时间内发起太多的图片请求,以及存在图片太大而有效显示区域较小。所以根据分析的结果,开发需要合理控制数量,可考虑使用雪碧图技术、拆分域名或在屏幕外的图片使用懒加载等。
图片在上传前在保持可接受的清晰度范围内同时减少文件大小,进行合理压缩。现如今有很多不错的图片压缩插件工具,就不在详情介绍了。
推荐一个比较优秀的图片压缩网站:TinyPNG使用智能有损压缩技术将您的 WebP, PNG and JPEG 图片的文件大小降低
更多编程相关知识,请访问:编程入门!!
Number of pictures | Does not support WebP | Supports WebP | |
---|---|---|---|
10 | 523K | (77% reduction) 315K | (86% reduction)
|
100 | 69M | (Reduced by 72%) 38M | (Reduced by 84%)
|
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!