You must have come across the pretty nice progressive image loading by Medium . First, it loads a small blurry image, and then fades in to the large image. José M. Pérez has dissected this technique in his article on how Medium & other sites achieve this. In this article you will learn how this effect can be implemented in React and achieve the same easily.
Before diving into the code, What is the value addition?
Images are powerful expression for content driven websites & applications. Considering the range of user device capabilities & network bandwidth, the technique around loading images become crucial. Developers must leverage modern techniques to build meaningful visual explorations for the users.
- Better placeholder , the thumbnails are very small, less than 2kB, its better than solid colours & loading spinners. It creates a better visual clue and makes the thumbnail aesthetically pleasing.
- Lazy loading. With Lazy Loading while all the small thumbnails are requested, the large images are only requests when they are within the viewport.
- Custom Tailored Image Sizes. CDN providers like Cloudinary allows you to perform dynamic transformation on the fly lets you generate these thumbnails easily and allows you to optimise the page size for the target device.
How Simple Progressive Image Loading is Achieved?
Simple breakdown of how this effect is achieved -
- Encapsulate the image in a container div.
- Load a tiny version of the image with the original image.
- Hide the original image till its loaded (Use the onload event for detection) and display the blurred version of the tiny version.
- Once the original image is loaded, hide the blurred version with fade in transition.
Note : Medium uses HTML Canvas to achieve the blur effect, for simplicity we can use CSS blur filter to achieve the same.
Here is the working demo of the ProgressiveImage Component in React. Feel free to fiddle with it.
Progressive-Image-Loading-Like-Medium - CodeSandbox
The online code editor tailored for web applications
I recommend that you use network throttling and disable cache to notice the full animation in action.
- Make sure you filter the props which are non <img> attributes and delegate to the actual <img> tag (line 39) so that the Component can be treated like any other image tag across your app. For instance if you want to set alt or add className the image tag.
- Capture onLoad into the state to determine the exit of the blurred overlay
- Use CSS filter & transition to animate the fade out effect. If you have not used CSS filter before you can learn more here
- I have added a clipPath to inset(0) which solves the problem of bleeding image pixels dues to CSS blur.
Quite simple right? If you have some questions please feel free to tweet them at me.
Follow me to stay updated with my posts. Have a great day! 🎉
(Originally published on Codeburst Medium)