There are 6 schemes to optimize the loading of web images:

  1. Image compression
  2. Load compressed image first, then load high definition large image, replace after loading (blur first, then clear)
  3. Media query device (different screen sizes)
  4. Use Base64, CSS, canvas instead of simple images
  5. Image preloading (preloading)
  6. Lazy loading of images (less then more)
  7. Use CDN acceleration

1. Image compression

Under the premise of no visual impact on the size of the image compression, can fundamentally solve the problem of slow loading pictures on the web page

Image compression is divided into two aspects:

  • One is to reduce the total number of pixels in an image

If the screen has 450 * 750 pixels, a large hd image of 1080 * 1920 is unnecessary and can be compressed using external software

  • Another is to reduce the number of bytes required per pixel

For example: each pixel of an image is stored by RGBA color value, R\G\B\A has 0 to 255 values for each color channel, i.e. 2^8 = 256. Exactly 8 bits 1byte. Each pixel has four channels, and each pixel requires 4bytes

RGBA color values can represent 256^4 colors, which is a large number, and usually we don’t need that many color values. So can we reduce the number of colors in the palette? This reduces the number of bytes per pixel.

Lossless compression is an algorithm that minimizes image storage volume while storing pixel data. For example, if one pixel in an image is very close to the surrounding pixels, such as a picture of a blue sky, we can store the difference between the color values of the two pixels, thus reducing the number of bytes per pixel

2. Load the compressed image first, then load the large hd image, and replace it after loading

The compressed image is photo_min.jpg and the corresponding high definition large image is photo.jpg

<body>
    <div class="box">
        <img src=".. /images/photos/culture/photo.min.jpg">
    </div>
</body>
<script>
    $(function() {
        // a re that matches all image SRC attributes of _min
        var test = /_min\./
            // Iterate over all image nodes
        $("img").each(function(index, obj) {
            if (test.test($(this).attr("src"))) {
                var reSrc = $(this).attr("src").replace(test, "."); // Complete the substitution
                $(this).attr("src", reSrc)
            }
        })
    })
</script>
Copy the code

3. Call the API to get the screen size and use images of different sizes based on the results

A 1920 × 1080 px computer screen requires a large image size, but a 320 × 640 px phone screen does not, so loading images of different sizes depending on the screen size is a solution.

4. Use Base64, CSS, and Canvas instead of simple images

For some relatively simple pictures can be base64, CSS, canvas and so on instead

Use Base64 instead of images

  • How it works: Converts an image to a Base64 encoded string inline to a page or CSS

background-image: url(“data:image/png; base64,iVBORw0KGgo=…” ); Or < img SRC = “data: image/PNG; base64,iVBORw0KGgo=…” />

  • Scenario: this method applies to the situation where the image size is smaller than 2KB and the total number of referenced images on the page is not large
  • Advantages: 1. Reduce the number of HTTP requests; 2. And can be put in the background database, only the transmission of strings, faster
  • If the picture is too large, the string is too long, which is not conducive to transmission

Use CSS instead of images

  • How it works: Use before or afterPseudo elementsTo enrich the complexity of the pattern.
  • Scenario: Suitable for mobile terminal or advanced browser, used for drawingSimple design.
  • Advantages: it has the characteristics of simple implementation and small image volume, and can achieve simple dynamic effects
  • Disadvantages: also limited by CSScompatibilityFeatures, drawingComplex patternsdifficult

Canvas instead of picture

  • Principle: HTML5The canvas element
  • Scene: Draw high performance pictures oranimation
  • Advantages: The whole is to draw 2D graphics, the page rendering performance is relatively high, page rendering performance is little affected by the graph complexity,Performance is only affected by the resolution of the graph, the drawn graphics can be directly saved as.png or.jpg graphics, suitable for drawing raster images or irregular graphics
  • Disadvantages: No DOM manipulation, must rely on timers, poor text rendering performance, can’t add image descriptions, compatibility limitations

The specific content of Canvas can be seen in the HTML series — Canvas

5. Preload resources

Resource preloading is a performance optimization technique that can be used to foretell browsers that certain resources are likely to be used in the future

DNS prefetch =” dnS-prefetch”

For example, if we might load an image called image.png in the future, we could add the following to the tag at the top of the document: A simple line of code tells compatible browsers to do DNS prefetch, meaning that when the browser actually requests a resource in the domain, the DNS has already been resolved

Perfecting rel = “prefetch”

Unlike DNS preresolution, prefetch actually requests and downloads the resource and stores it in the cache

Add the following to the tag at the top of the document:

Pre-rendered rel = “prerender”

For a TAB page that a user will definitely open in the future: download all the resources, create the DOM structure, complete the page layout, apply CSS styles, execute JavaScript scripts, etc. When the user actually visits the link, the hidden page switches to visible, making the page appear to load instantaneously

The premise is that the user must open the TAB page in the future; otherwise, unnecessary resources will be wasted

6. Lazy loading of images

Load when the user is about to see the image, not if the bit is in the viewport area

Implementation idea: listen to the bottom event

Wechat applets

// there is a method onReachBottom() in the Page of wechat applet that can listen for users' pull-up events
Page({
    onReachBottom(){
        /* Start request to load image */}})/ / the JSON file
{
    "onReachBottomDistance": 50 // The distance to the bottom of the page when the pull-up event is triggered, in unit of px
}
Copy the code

Web side

// THE html5 + vue implementation listens for user pull-up events
mounted () {
    window.onscroll = function(){
        var scrollTop = document.documentElement.scrollTop // The distance from the top of the current screen to the top of the scroll bar
        var clientHeight = document.documentElement.clientHeight // The height of the screen viewable area
        var scrollHeight = document.documentElement.scrollHeight // The total height of the scroll bar
        if(scrollTop + windowHeight + 50 == scrollHeight){ 
            /* To start loading images, reserve 50px */}}}Copy the code

7. Use CDN to accelerate resource acquisition

Details on CDN acceleration can be found in the browser series – CDN Acceleration