Intersection Observer is a built in browser API which allows you to detect when an element is visible in the viewport. It is supported by most modern browsers but with small polyfill you can make it work with unsupported browsers such as Internet Explorer.
If you plan to support old browsers like IE in your website make sure your load this polyfill before the code below.
Lazy Loaded Images
To lazy load images first we need to prepare our existing images to support this feature.
As default all html
img tags support the
src attribute but by placing the image path into this attribute will cause the browser to consume (load it) right away. That means even if the image is not the the viewport it will be loaded by the browser. This is not a bad thing but when you are aiming for speed and improvement it’s definitely the right approach.
To fix this we need to pass the image source to another attribute. You can name this attribute however you want as long it complies to HTML5 data attribute standards, but the most common way it’s
data-src. We will also add a class name to all our images that need lazy loading.
So what if we don’t provide any
src attribute? Will it cause errors? The answers is no, but the best way to do it is to provide a 1×1 pixel placeholder image to all our images. Why 1×1 pixels? Because it basically takes no time to the browser to load it and when our actual image gets loaded it will replace this placeholder.
src value to the one from
data-src, adds a “loaded” class (it’s not mandatory but you can do cool stuff with it – like fade in animations) and after that it calls the
unobserve method to stop looking over that particular image.
Only and only when the image path it’s passed from
src, the browser will load the image.
So after adding a little bit of CSS for some cool fadein animation, here is the final result.
Why Intersection Observer?
Because speed. Simple as that. Your website needs to be as fast as possible nowadays and search engines care a lot about your loading speed. Of course this is just a tiny improvement when we talk about speed improvements, but still a faster website can make you surpass your competitors and lazy loading your images it’s something that you need for that.