当前位置:网站首页>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

a4ae421d5ff986ab8aa22022ea240821.png

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

c18ecb832b8b2f488b40de505c6d105d.png

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 .

3e7e05599c640b6c286b8aecd87e78b3.png

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.

d567b7a7b783dc045a8f3d4e46d3c79a.png

Let's take a look at the example :

fea08178dab404bf35f9999d40195f4b.png

Detail display :

5c491f2add551f3120337ecf35b6cc8e.png

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 .

193f7b5dfa46234e585e3f998563915d.png

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.

999f4229d7326ff846c3b17795cfd542.png

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

38d5dbbf5d86fff397dbd1240672ea4b.png

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:

6571d6ea0ed50d488fcc9383d37357ed.png

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 ).

0ac8a6f83b74e5ebb2415ba6bf8256eb.png

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 .

c1981fb530042bc06172f012b7e2b9b1.png

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 .

ad88effe75470a01683af47bf8357906.png

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 .

b4ae02d8c6e5b8947a5c4a8e7ee0080a.png

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

7013b31a83f73e637fbc0798eb001534.png48a40b88883ae0e3cade17a93eab0be9.png

Business scenario

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

f96cb29e2cfbc9b4782783a3c83c2e1a.png

Picture format summary

I've sorted it out for you Mind mapping :

067bda4902dedf6addaaf9ecde89fe16.png

OSS collocation CDN

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

a9f781aa54e151e96a43eefa4c876404.png

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 .

79ebe5eb70d5ddec5138f531866c13b1.png

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/)

原网站

版权声明
本文为[zz_ jesse]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/172/202206211015301268.html