Lazy Loading Images and Video
Last updated
Last updated
Lazy loading is technique that defers loading of non-critical resources at page load time. Instead, these non-critical resources are loaded at the moment of need.
Because it’s possible you’re loading stuff the user may never see:
It wastes data. Be a waste of their money.
It wastes processing time, battery, and other system resources.
When we lazy load images and video, we reduce initial page load time, initial page weight, and system resource usage, all of which have positive impacts on performance.
The most common lazy loading candidates are images as used in <img> elements.
When we lazy load <img> elements, we use JavaScript to check if they're in the viewport.
If they are, their src (and sometimes srcset) attributes are populated with URLs to the desired image content.
If you've written lazy loading code before, you may have accomplished your task by using event handlers such as scroll or resize.
Modern browsers offer a more performant and efficient way to do the work of checking element visibility via the intersection observer API.
Intersection observer is easier to user and read but it’s not universal.
Best way to use lazy loading with Inline images is: Intersection + event handlers.
The url is declared in css: background-image.
When resource in screen we’ll add image to contents by add css class.
1.For videos where playback is initiated by the user (i.e., videos that don't autoplay). Use preload attribute.
2. Use poster attribute which lets you specify a placeholder.
For video acting as an animated GIF replacement.
They play automatically when loaded.
They loop continuously.
They don't have an audio track.
React-lazyload (only react)
So much benefits but not easy.
If you get it wrong, there could be unintended consequences.
I will show you some note.
Some note:
Layout shifting and placeholders.
Image decoding delays.
When stuff doesn't load.
JavaScript availability.
Layout shifting and placeholders:
What happen if shifting in the layout if placeholders aren't used ?
Trigger expensive DOM layout operations that consume system resources.
For <img> tags, src should initially point to a placeholder until that attribute is updated with the final image URL. The poster attribute in a <video> element to point to a placeholder image. Additionally, use width and height attributes on both <img> and <video> tags.
Image decoding delays:
Loading large images in JavaScript and dropping them into the DOM can tie up the main thread. Block screen. => Asynchronously decoding images using the decode method.
When stuff doesn't load :
Sometimes media resources will fail to load for one reason or another and errors occur.
JavaScript availability :
It should not be assumed that JavaScript is always available.
Source: Google Developer