Lazy Loading images with fade in
Loading large images can cause a delay in the initial paint for your page, a possible solution for this is to show a placeholder image instead then swap in the original image after loading.
Creating a low-res version of your image will reduce the file size, giving you a much quicker loading time but the resulting image will be of much lower quality when displayed at the original size. You can apply CSS filters to blur this image, then once the original image has loaded use a CSS transition to gradually remove the blur and bring the full-res image into focus, without the user being aware a low-res image was initially loaded.
Preload
In order to lazy load the image a rel="preload"
link can be added to the page - see Preloading content with rel=”preload” on MDN web docs this allows the resource to be downloaded as soon as possible without blocking the page render.
Once the resource has loaded a JavaScript function can be triggered using the onload attribute, which we can use to swap the full image for the low-res version.
Example preload link
<link rel="preload" href="large-image.png" as="image" onload="swapImage">
CSS Blur
The blur filter will let us blur the original image when first displayed, and we can use a transition on the filter in order to gradually remove the blur when the full image is loaded:
.before {
filter: blur(10px);
transition: filter 3s ease-in;
}
.after {
filter: blur(0px);
}
Example
For this example, I’ve used one of my pictures from Flikr, note the image has not been optimised in any way, normally you would make sure you are serving an image size as close to the final size as possible instead of just taking the image and resizing it in the browser. The original image is over 1Mb, the reduced image is approx 1.2Kb, inlined as a data URI:
Codepen demo of lazy load:
See the Pen Lazy load fade in image by Neil Lupton (@Neil188) on CodePen.