Problem: Sometimes we render large images on a web page, but the images tend to trickle out linearly and the user experience is not very good

Like this

To solve this problem, I put together several optimizations

  • Preload using the link tag preload
  • Image resolution
  • Replace the image onload with another style
  • The background color
  • After compressing the image, go to Base64

1. Look at the first preload method

<link rel="preload" href="./img/all.jpg" as="image" />
Copy the code

When added, the browser loads the image before rendering, so that the image is displayed as a whole

And this way at all ends support is ok, and then look at the second way

2. Split images

Now the big image is 5MB, I split it into 9 smaller images of over 400 KB, now look at the effect

As you can see, the experience has improved a little bit, but I’m actually stealing a little bit of slack here. It would have been better if I had a smaller floor

3. Replace the image onload with another style

Img will trigger onload event after rendering, so we can first set the image to hide, put an image or load to transition, and then switch after the image triggers onload event. In addition, some CDN can also obtain blurred images through the query parameter. This way we can achieve fuzzy to clear progressive loading

4. Background color

Pre-set the wrap element of the image with a background color that matches the overall tone of the image

5. Turn base64

The image will appear as a whole, but it is not recommended to enlarge the image, otherwise your code will be very long