当前位置:网站首页>Performance optimization - image compression, loading and format selection
Performance optimization - image compression, loading and format selection
2022-06-21 10:17:00 【zz_ jesse】
This article starts from the front-end team blog of Zhengcai cloud : performance optimization —— Picture compression 、 Loading and format selection
https://www.zoo.team/article/images-compress

Preface
I'm sure you've heard of it "258 principle (https://blog.csdn.net/weixin_42139375/article/details/83001248)" , The performance of a website will greatly affect the user experience .
After I went through several e-commerce and large screen projects to optimize the performance , I find Image resources The process of Web site performance optimization plays an important role .
General e-commerce websites request data

Loaded on the first screen 145 Of the requests, picture resource requests account for 75% above , Pictures also account for a large proportion of all requested static resources . This shows the importance of image optimization .
But before we know about image optimization Binary digits And Color rendering The relationship between .
Binary digits and colors
In the computer , Generally, binary numbers are used to represent pixels . In different picture formats , The corresponding relationship between pixels and binary digits is different . The more binary digits a pixel corresponds to , It can represent a variety of colors , The more sophisticated the imaging effect is , The storage space required for pictures will be correspondingly larger .

At present, there are many ways to optimize image resources in the market , Such as compressed pictures 、 Choose the correct format 、 CDN Speed up 、 Lazy loading, etc .
The compressed image
The compressed image It is believed that this is the first plan that everyone came up with . Like we are familiar with tinpng (https://tinypng.com/), His principle is to have " selectivity " Reduce the number of colors to be stored in the image , To reduce the memory needed to store pictures .
“When you upload a PNG (Portable Network Graphics) file, similar colors in your image are combined. This technique is called “quantization”. By reducing the number of colors, 24-bit PNG files can be converted to much smaller 8-bit indexed color images.

Let's take a look at the example :

Detail display :

Image format
The compressed image Although to a certain extent, it can reduce the resources we need bandwidth , But if you use it right Format There are often qualitative changes in performance .
JPEG / JPG
JPEG Is the most commonly used image file format .
advantage
Support extremely high compression ratio , Can make file transfer 、 download 、 Preview speed is much faster .
With variable compression ratio, you can control the file size .
Can handle easily 1600 Ten thousand colors , It can reproduce full-color images very well .
defects
JPG The lossy compression of Shuffling figure and Background map It's really hard to see flaws in the exhibition of , But when it deals with vector graphics and Logo Strong sense of line 、 When the color contrasts strongly with the image , Caused by artificial compression Blurred picture It will be quite obvious . Therefore, this format is not suitable for displaying high definition and Strong sense of line Image .
besides , JPG It does not support the display of images with transparency requirements , If you need to show Transparent picture Still need to find another way .

Business scenario
JPG It is suitable for presenting colorful pictures , In our daily development ,JPG Pictures are often used as large Background map 、 Shuffling figure or Preview appear . Open the homepage of an e-commerce website , You can see that the processing of large images is almost always used JPG.

PNG - 8 And PNG - 24
png Is a bitmap format using lossless compression algorithm .
advantage
lossless compression
Fully support alpha transparency .
Can be saved repeatedly without degrading image quality .
shortcoming
It's too big

Business scenario
In theory , When you pursue the best display effect ( Detailed display diagram 、 The picture needs to be enlarged 、 Photography, etc ), And don't care about the storage size or the required bandwidth , have access to PNG-24 (https://baike.baidu.com/item/PNG/174154?fr=aladdin). But in practice , To avoid the problem of large file size , We usually don't PNG To process more complex images . When we meet the right PNG When , Will also give priority to smaller PNG-8 .
Or when you need to deal with pictures with transparency or obvious lines , Will also use PNG . Such as webmaster logo:

SVG
Strictly speaking, it should be an open standard vector graphics language .
advantage
Scalable , It can support infinite amplification
A programmable
shortcoming
Not all browsers support SVG,IE8 And earlier versions need a plug-in .
Complex images slow down rendering ( Only small graphs are supported ).

Business scenario
SVG It's a text file , We can define it just like writing code SVG , Write it in HTML in 、 Become DOM Part of . What we use more is iconfont (https://www.iconfont.cn/). We can set the module's fill Attributes easily adapt to the icon's skin changing function , And pass font-size Adjust its size .

Base64
Based on the 64 A printable character to represent binary data .
advantage
Reduce network requests
For dynamically generated images in real time, it is not necessary to store the images in the server to occupy server resources
shortcoming
Only suitable for small pictures .
If the image needs to be replaced frequently, the whole code needs to be replaced , Low maintainability .
Business scenario
Base64 and Sprite equally , It exists as a small icon solution .
“Base64 It is used for transmission 8Bit Encoding method of bytecode , Through the picture Base64 code , We can write the coding result directly to HTML Or write CSS , Thereby reducing HTTP Number of requests .
stay Elements Mid search “base64” keyword , You'll find that Base64 There are also many places to use . And its corresponding image occupies less memory .

since Base64 That's great , We use all the pictures Base64 All right .
Base64 After the coding , The image size will be expanded to the original file 4/3( Base64 Coding principle (https://blog.csdn.net/wo541075754/article/details/81734770)). If we code the big picture to HTML or CSS In file , The volume of the latter will increase significantly , Even if we reduce HTTP request , It can't make up for the performance cost of this huge volume . That is to say, what we sacrifice Rendering performance Greater than Resource request performance , It's not worth it .
We can see , Most use Base64 The encoded pictures are all small pictures .

WebP
One provides both lossy and lossless compression ( Reversible compression ) The image file format of .
advantage
Support is lossless
Small footprint
Can support transparency
shortcoming
Poor compatibility


Business scenario
Same as JPEG/JPG . Because the compatibility is not good at present , General collocation JPEG/JPG Use it together .

Picture format summary
I've sorted it out for you Mind mapping :

OSS collocation CDN
Our original method is to put resources such as pictures into the project, package them and go online .

The disadvantage of this is that the package is too big to say , The speed at which users request resources is also limited . For example, our server is in South China , User requests in North China will be slightly slower . When there is a large amount of concurrency , Requesting interfaces and resources from the deployment server is nothing more than putting extra pressure on our server . When we want to replace a picture temporarily , It also needs to be repackaged and released online , Very trouble .

When we take pictures OSS Place and CDN After acceleration , This problem has been well solved . Users in different regions can access the nearest server , Repeated requests also generate caches , avoid OSS Waste of flow .
《OSS and CDN The difference between 》(https://www.cnblogs.com/jsfh/p/14076992.html) You can also refer to this article for a closer look .
Lazy loading of pictures
I'm sure you will encounter too much data on the first screen and slow loading . In this case, we need to consider lazy loading . When the user scrolls to the preview position , Requesting picture data . Use skeleton screen or thumbnail instead .
window.onload = function () {
// Get a list of pictures , namely img Tag list
var imgs = document.querySelectorAll('img');
// Get the distance to the top of the browser
function getTop(e) {
return e.offsetTop;
}
// Lazy loading implementation
function lazyload(imgs) {
// Height of visible area
var h = window.innerHeight;
// Scroll area height
var s = document.documentElement.scrollTop || document.body.scrollTop;
for (var i = 0; i < imgs.length; i++) {
// When the distance between the image and the top is greater than the sum of the visible area and the scrolling area, the image will be loaded lazily
if ((h + s) > getTop(imgs[i])) {
// The truth is that the page starts with 2 Second blank , So use setTimeout timing 2s
(function (i) {
setTimeout(function () {
// Execute the function immediately without adding i It will be equal to 9
// Load pictures or other resources invisibly ,
// Create a temporary picture , This picture will not go to the page in memory . Realize invisible loading
var temp = new Image();
temp.src = imgs[i].getAttribute('data-src');// Only once
// onload Judge that the picture is loaded , The picture is loaded , Assigned to it again dom node
temp.onload = function () {
// Get custom properties data-src, Replace the fake picture with the real picture
imgs[i].src = imgs[i].getAttribute('data-src')
}
}, 2000)
})(i)
}
}
}
lazyload(imgs);
// Scrolling function
window.onscroll = function () {
lazyload(imgs);
}
}The end of the
performance optimization It is a hard skill that our front-end development engineers must master . Unlike learning other new technologies , When you want to learn a new framework , Reading documents and source code can almost make you comfortable in the process of use . But performance optimization is different , It can only let us explore, understand and break through , It's an experience, a habit, and a sense of smell .
Reference material
Best practices : Use alicloud CDN Speed up OSS visit (https://developer.aliyun.com/article/770616?utm_content=g_1000173381)
The nuggets pamphlets : Principle and practice of front-end performance optimization (https://juejin.cn/book/6844733750048210957)
Wallpaper website : wellhaven (https://wallhaven.cc/)
边栏推荐
- Talk about the multimodal project of fire
- Cvte side
- Eig and Saudi Aramco signed a memorandum of understanding to expand energy cooperation
- Embedded software project process and project startup instructions (example)
- 聊聊大火的多模态项目
- 注解的定义以及注解编译器
- [actual combat] STM32 FreeRTOS migration series tutorial 2: FreeRTOS mutually exclusive semaphores
- Judge the data type of JS
- 远程办公市场调查报告
- 1. is god horse a meta universe?
猜你喜欢

New programmers optimize a line of code on Monday and are discouraged on Wednesday?

The execution process before executing the main function after the DSP chip is powered on

还在直接用localStorage么?全网最细:本地存储二次封装(含加密、解密、过期处理)

基因型填充前的质控条件简介

Xidian AI ranked higher than Qingbei in terms of AI major, and Nantah ranked first in China in terms of Software Science in 2022

简易的安卓天气app(三)——城市管理、数据库操作

安全百强 中坚力量!美创科技入选《2022年中国数字安全百强报告》

AI越进化越跟人类大脑像!Meta找到了机器的“前额叶皮层”,AI学者和神经科学家都惊了...

The more AI evolves, the more it resembles the human brain! Meta found the "prefrontal cortex" of the machine. AI scholars and neuroscientists were surprised

TensorFlow,危!抛弃者正是谷歌自己
随机推荐
Ccs7.3 how to erase only part of the flash sector when burning DSP on-chip flash (two projects of on-chip flash burning of a DSP chip)
触摸按键控制器TTP229-BSF使用心得[原创cnblogs.com/helesheng]
嵌入式软件项目流程、项目启动说明书(示例)
Unity中的地平面简介
Comparison between JWT and session
[cloud native | kubernetes] kubernetes configuration (XV)
Brief introduction of quality control conditions before genotype filling
并发底层原理:线程、资源共享、volatile 关键字
如何选择嵌入式练手项目、嵌入式开源项目大全
113. summary of common usage of moment.js
Odd number of characters异常
为什么 C# 访问 null 字段会抛异常?
Mythical games announced its cooperation with kakao games, a leading Korean game publisher, to promote business expansion in the Asia Pacific Region
js正则-梳理
基因型填充前的质控条件简介
Use this for attributes in mapstate
Eureka的TimedSupervisorTask类(自动调节间隔的周期性任务)
国金证券开户安全吗?
TC software outline design document (mobile group control)
Audio and video synchronization knowledge points you must pay attention to: