Lazyloading :

Lazyloading is a technique used in web development to delay the loading of non essential resources such as images and videos or script until they are needed.
Lazy loading helps faster Initial Load time ,Improves Performance,Enhances user Experience.

Loading Attribute :

Here is an example demonstrating lazyloading of images using the loading attribute

loading attribute allows a browser to defer loading offscreen image and i frames
Delays loading the resources images or iframe until about to enter the viewport. Ideal for below the fold content like galleries , embedded videos or scroll pages.

Intersection Observer API :
Here is an example demonstrating lazyloading of images using the Intersection Observer API

data-src is a custom attribute ,it’s stores the actual image URL temporarily without loading it right away .

Code Explanation :

  • const lazyImg =document.querySelector(‘.lazy’); –> this should be ‘queryselectorall ‘ if want to select all images .
  • const observer = new IntersectionObserver((entries,observer)=>{} –> it watches to see when they come into the viewport.
  • entries.forEach(entry =>{} –> Loops through every observed element image that changed visibility
  • if(entry.isIntersecting){} –> This checks if the image is visible on the screen , only then do we load it
  • const img = entry.target –> get the image element
  • img.src=img.dataset.src –> Image starts loading
  • img.classList.remove(‘lazy’) –> Remove the lazy class
  • observer.unobserve(img) –> stop observing this image since it’s already loaded.
  • lazyImg.forEach(img=>observer.observe(img)) –> whenever they appear on screen the observer will trigger load them.

Benefits of lazyloading : Faster page load improves performance & scrolling Saves user bandwidth Reduces the server load Load’s only what’s needed

Lazyloading is used image galleries , e-commerce product lists ,embedded videos ,infinite scroll pages, mobile apps,long landing pages and dynamic content loading .

Leave a Reply