This article is taken from my public account [Sun Wukong, Don’t talk nonsense]

The need for

Does image optimization matter?

As a developer, intuitive sense: important! We have tried many, many optimizations in engineering to reduce the final code file size, and the final optimization size can be several hundred KB. However, an image on a web page can easily be hundreds of kilobytes in size.

If the intuition isn’t obvious enough, let’s take a look at the site’s statistics. The http-Archive periodically captures sites on the Web and records the loading status of resources. The statistical results for the past year are as follows:

As you can see, half of all Web requests are requests for images. Isn’t that a little surprising?

Both Yahoo’s catch-all and Google’s official best practices list image optimization as an essential part of front-end performance optimization — the priority of image optimization is evident.

Applicable scenarios for different formats of pictures

Widely used Web image formats include JPEG/JPG, PNG, WebP, Base64, SVG and so on, which have their own characteristics.

Next, we will expand these formats in detail from the aspects of advantages, application scenarios and disadvantages.

JPEG/JPG

advantages

The biggest feature of JPG is lossy compression. This efficient compression algorithm makes it a very lightweight image format. On the other hand, even though it is called “lossy” compression, JPG compression is still a high quality compression: when we compress an image to less than 50% of its original volume, JPG still retains 60% of its quality. In addition, the JPG format stores a single image in 24 bits and can present as many as 16 million colors, enough to handle the color requirements of most scenarios, which means that the mass loss before and after compression is not easily detected by our human eyes.

Applicable scenario

JPG is good for rendering colorful images, and in our daily development, JPG images are often used as large background, rotation, or Banner images.

Using JPG to render large images, which can preserve image quality without causing headaches in image volume, is one of the most popular solutions nowadays.

disadvantages

Lossy compression is hard to spot on the rote images shown above, but when it comes to images with strong lines and color contrast, such as vector graphics and logos, the resulting blur can be quite noticeable.

In addition, JPEG images do not support transparency processing, and transparent images need to be rendered in PNG.

PNG

advantages

PNG (Portable Network Graphics Format) is a lossless compression image format with high fidelity. 8 and 24, these are the bits of binary numbers. According to the corresponding relationship mentioned in our previous knowledge, 8-bit PNG can support up to 256 colors, while 24-bit PNG can present about 16 million colors.

PNG images have stronger color expression than JPG, more delicate processing of lines, and good support for transparency. It makes up for the limitations of JPG mentioned above, the only problem is that it is too big.

When to use PNG-8 and when to use PNG-24 is a question.

In theory, pNG-24 is recommended when you’re looking for the best display and don’t care about file size.

In practice, however, PNG is not used for more complex images in order to avoid volume issues. When we came across scenes that were suitable for PNG, we preferred the smaller PNG-8.

How to determine whether an image should be pNG-8 or PNG-24? It’s a good idea to export images in both formats first, see if pNG-8 output results in a visually visible loss of quality, and determine if this loss is acceptable to us (especially your UI designers) based on the comparison.

Applicable scenario

As mentioned above, the cost of processing complex and colorful images with PNG will be relatively high, so we usually hand over JPG to store them.

Considering PNG’s advantages in handling lines and color contrast, we mainly use it for small logos, simple and contrasting images or backgrounds, etc.

disadvantages

Too big is the only BUG.

SVG

SVG (Scalable Vector Graphics) is an image format based on XML syntax. It is fundamentally different from the other image types mentioned in this article: SVG does not process images based on pixels, but rather on the shape description of the image.

advantages

The most performance related aspect is that SVG has smaller and more compressible files than PNG and JPG.

Of course, as a vector graph, its most significant advantage is that the picture can be infinitely enlarged without distortion. This allows SVG to maintain good image quality even when placed on a retina screen — one SVG is good enough for n resolutions.

Additionally, SVG is a text file. We can either define SVG as code, writing it in HTML as part of the DOM, or we can write descriptions of graphics in separate files with an.svg suffix (SVG files are used just like normal image files). This allows SVG files to be read and modified by a wide variety of tools, giving them great flexibility.

Applicable scenario

SVG is a text file, and we can either define SVG as code, write it in HTML as part of the DOM, or write the description of the graph in a separate file with an.svg suffix (SVG files are used just like normal image files).

In real development, we use the latter more often. In many cases designers will give us SVG files, and even if we don’t have designers, we have a very good vector graphics library online.

disadvantages

SVG has two major limitations. One is its high rendering cost, which is detrimental to performance. SVG, on the other hand, has a learning cost (it’s programmable) that other image formats don’t.

Base64

Base64 is not an image format, but an encoding method.

Applicable scenario

We might as well open taobao home, and then open the developer tools, in the source search “base64” keyword, you will find base64 code in the place really many. And the corresponding image is often a very small Logo.

Since Base64 is so great, why don’t we change the big picture to Base64, too?

This is because, after Base64 encoding, the image size will swell to 3/4 of the original file size (this is determined by Base64 encoding principle). If we coded large images into HTML or CSS files, the size of the latter would increase significantly, and even if we reduced HTTP requests, the performance cost would not be worth the cost. When transferring very small images, Base64’s bloated file size and the time it takes the browser to parse Base64 are negligible compared to the COST it saves on HTTP requests, where the real performance benefits come into play.

Therefore, Base64 is not a foolproof solution, and we tend to apply Base64 encoding to an image when it meets the following criteria:

  • The actual size of the picture is small
  • Images cannot be combined with other small images in Sprite form (Synthetic Sprite is still the main way to reduce HTTP requests, Base64 is complementary to Sprite)
  • Image update frequency is very low (no need for us to repeatedly encode and modify the file content, low maintenance cost)

WebP

WebP is one of the youngest image formats present today. It was proposed in 2010. It is a picture format developed by Google for the Web to speed up the loading of pictures.

advantages

WebP is handy for detailed images like JPEG, supports transparency like PNG, and displays dynamic images like GIF – it combines the best of many image file formats.

WebP’s official introduction puts this point more authoritatively:

Compared to PNG, WebP lossless images are reduced in size by 26%. WebP lossy images are 25-34% smaller than comparable JPEG images under the equivalent SSIM quality index. Lossless WebP supports transparency (also known as alpha channel) with only 22% extra bytes. For cases where lossy RGB compression is acceptable, lossy WebP also supports transparency, typically providing 3 times the file size compared to PNG.

Image optimization is a game between quality and performance, from this point of view, WebP is undoubtedly the real winner.

disadvantages

WebP may be good, but it’s too young. As we know, any new thing can’t escape the big hole of compatibility.

In addition, WebP adds to the server’s burden — coding a WebP file of the same quality takes up more computing resources than coding a JPG file.

Applicable scenario

The biggest issue limiting our use of WebP right now is not the “does this image fit WebP” issue, but the “does the browser allow WebP” issue, the compatibility issue we talked about earlier. Specifically, once we choose WebP, we need to consider that it will not display in Safari and other browsers, which means we need to prepare PlanB, prepare the downgrade plan.

If you decide to use WebP, compatibility handling is essential.

us

After seeing different types of pictures corresponding to different applicable scenes, will you have some feelings and ideas?

What kind of pictures to choose? There is another aspect to optimization: is it necessary to load images? After all, being able to not load images is a best-case scenario.

Now, let’s talk about lazy loading of pictures.

Lazy loading of images

The so-called “do more wrong, do less wrong, do not do good”. In the process of performance tuning, the best tuning result is: no request is sent. The same is true for image optimization.

Image lazy loading in some image – intensive sites to use more.

Lazy image loading allows some images that are not currently visible to be not loaded, avoiding blocking requests caused by loading too many images at one time (browsers generally limit the number of concurrent requests under the same domain name), which improves the loading speed of websites and improves user experience.

Train of thought

For image lazy loading, the basic idea is this: as long as the image is not in front of the current view, do not load. Select load only when the corresponding image is monitored to appear in the current visual window. Here’s what you can do:

The first step: In HTML, the SRC of the img tag that needs lazy loading is set to thumbnail or not set to SRC, then you define a property that is the address of the real image or the original image (such as data-src below), and define a generic class name that indicates that the image needs lazy loading (such as lazy-image in the following example, You can also use the IMG element (suboptimal), which serves two purposes:

2. You can set the background image of this class name as the excessive image before the image is loaded, for example, the image displayed as loading.

  //HTML
  <img data-src="https://bji/cms/banner_20191212_2.jpg" class="lazy-image"/> //CSS attribute. Lazy-image {background: url('.. /img/loading.gif') no-repeat center; 
} 
Copy the code

Step 2: After the page is loaded, we need to get the set of elements of all images that need lazy loading and determine if they are in the visible area. If so, set the SRC attribute of the element to the address of the real image.

More specifically, there are two ways to determine whether you are in the visible area.

Method 1: getBoundingClientRect

inViewShow() {     
    let imageElements = Array.prototype.slice.call(document.querySelectorAll('.lazy-image'))    
    let len = imageElements.length     
    for(let i = 0; i < len; i++) {         
        letConst imageElement = imageElements [I] the rect. = imageElement getBoundingClientRect () / / loading picture came into viewif(the rect. Top < document. DocumentElement. ClientHeight) {imageElement. SRC = imageElement. Dataset. The SRC / / remove have shown imageElements.splice(i, 1) len-- i-- } } }Copy the code

The top value in the getBoundingClientRect attribute of the element is compared with the clientHeight of the page. If the top value is less than clientHeight, the element is in the visible area. The BoundingClientRect function gets the set of positions of an element relative to the view, as shown in the following figure. “Bottom” and “right” are not the same as “right” and “bottom”.

Intersection Observer

Above we use the top attribute of the BoundingClientRect and the clientHeight of the body to determine whether an element is visible. This traditional method of getting an element visible has one determination: it needs to listen for the Scroll event. Scroll events are very easy to occur and can be a waste of resources with a lot of computation.

A new Web API is Intersection Observer, which calls a callback whenever an element is visible, without listening for scroll events. Inside the callback, we call the corresponding element’s processing logic when it is visible.

if ("IntersectionObserver" in window) {        
    letLazyImageObserver = new IntersectionObserver((entries, observer) => {entries.foreach ((entry, index) => {// If the element is visibleif (entry.intersectionRatio > 0) {              
                let lazyImage = entry.target              
                lazyImage.src = lazyImage.dataset.src              
                lazyImage.classList.remove("lazy-image")              
                lazyImageObserver.unobserve(lazyImage)              
                // this.lazyImages.splice(index, 1)            
            }          
        })        
    })        
    this.lazyImages.forEach(function(lazyImage) { lazyImageObserver.observe(lazyImage); })}Copy the code

conclusion

This article mainly tells about two knowledge about picture optimization: different format picture applicable scene, picture lazy loading. Image optimization is a big step in performance optimization, I hope it will help you.


Front-end performance optimization series:

(a) : start with the TCP three-way handshake

(two) : for the blocking of TCP transmission process

(3) : optimization of HTTP protocol

(IV) picture optimization

(v) : browser cache strategy

(vi) : How does the browser work?

(vii) : Webpack performance optimization