What is lazy loading?
Loading images on the web is a fairly common task of web browsers. Take the example of image galleries, blogs, food recipe sites - all utilise images extensively and therefore have the focus on getting them loaded as soon as possible.
In the dictionary of programming, there are essentially two ways of loading resources: eager loading where a resource is requested for as soon as it is called for in the script, and lazy loading where a resource is requested only once it's needed.
Fortunately, these two ways also apply to resources in an HTML document:
For example if you have an image on a web page, then, according to the principle of lazy loading, it will only load when you scroll it into the viewport. Compared to this, a normally loaded image will load regardless of whether it appears in the viewport or not.
But what’s the catch in this way of loading stuff? Good question. Let’s see what lazy loading offers us.
Why lazy loading?
Lazy loading essentially optimises a web page by reducing its loading times and bandwidth usages.
Reduces loading times
A web page with 10 images normally loaded, will keep the loading icon on the browser spinning until the point all images are loaded. Although this won't hurt in most cases, it does however look bad. It gives somewhat an impression that the web page is not optimised and that it just keeps on loading forever.
In contrast, a web page with 10 lazy images would stop the icon spinning just after the web page loads. Lazy images don't request for any URL's with the load of the page and hence the browser thinks that everything has been loaded.
Furthermore, normally-loaded images affect the firing of the
onload event on a web page. This means that until all images on the page are loaded completely, any code dependent on this event won't be executed.
What we ideally want is to get the event fired as quick as possible and this can be done only if we employ the technique of lazyily loading images.
Reduces bandwidth usages
In addition to decreasing loading times; lazy loading can save literally tons of bytes of bandwidth for heavy traffic websites.
If a user doesn’t scroll down to see an image then why request for it? Why spend cellular data unreasonably in something no one sees. This is just what lazy loading thinks and does for you. It doesn't waste data in loading images that never appeared in the viewport. Only if they do, are they sent in the process to be loaded.
Well now that you know the benefits of lazy loading it is the high time to start off learning how to implement it actually in websites. Lazy loading is a good thing to know and learning its internal workings is even a better thing to be aware off.
So why waste anymore time in all this discussion and not just go straight into the work. Let's proceed!