Lazy Loading in JavaScript Examples

Lazy loading is a technique used in computer programming to defer the initialization of an object until the point at which it is needed. This can help to improve performance and reduce memory usage by avoiding the creation of unnecessary objects. In web development, lazy loading is often used to defer the loading of images or other resources until they are visible on the screen, which can improve the loading time of a web page.

Lazy Loading Implementing Methods

There are several ways to implement lazy loading in JavaScript, depending on the use case and the framework being used. Some common methods include:

It's also important to note that you should choose the method that best fits your requirements and use case.

Lazy Loading Best Practices

When implementing lazy loading in JavaScript, it's important to consider the following best practices:

Lazy Loading Image Example

Here's an example of how you might use lazy loading in JavaScript to load images in an HTML document:


<img data-src="image1.jpg" class="lazy-load"> 
<img data-src="image2.jpg" class="lazy-load"> 
<img data-src="image3.jpg" class="lazy-load"> 

// Get all the images with the lazy-load class 
var images = document.querySelectorAll('.lazy-load'); 
// Create an IntersectionObserver 
var observer = new IntersectionObserver(function(entries) { 
 // Loop through each entry 
 entries.forEach(function(entry) { 
 // If the entry is in the viewport 
 if (entry.intersectionRatio > 0) { 
 // Get the image 
 var image = entry.target; 
 // Set the src of the image to the data-src 
 image.src = image.getAttribute('data-src'); 
 // Remove the data-src attribute 
 image.removeAttribute('data-src'); 
 // Stop observing the image 
 observer.unobserve(image); 
 } 
 }); 
}); 
// Loop through each image and observe it 
images.forEach(function(image) { 
 observer.observe(image); 
}); 

In this example, we're using the IntersectionObserver API to detect when an image comes into the viewport. We first select all the images with the class lazy-load and then observe each image using the observer. When the image comes into the viewport, the IntersectionObserver callback is triggered and we update the src attribute of the image with the value of the data-src attribute and remove the data-src attribute.

This way the browser will only load images that are visible in the viewport and the others will be loaded when they scroll into the viewport.

You can also use a library like LazySizes, which provides a simple API for customizing the behavior and fallback for older browsers.

Lazy Loading Video Example

Here's an example of how you might use lazy loading to load a video in JavaScript:


<div class="video-container"> 
 <video class="lazy-load" data-src="video.mp4"></video> 
 <button class="play-button">Play</button> 
</div> 

var videoContainer = document.querySelector('.video-container'); 
var video = document.querySelector('.lazy-load'); 
var playButton = document.querySelector('.play-button'); 
playButton.addEventListener('click', function() { 
 // set the source of the video to the data-src 
 video.src = video.getAttribute('data-src'); 
 // Remove the data-src attribute 
 video.removeAttribute('data-src'); 
 // Play the video 
 video.play(); 
 // Hide the play button 
 playButton.style.display = 'none'; 
}); 

In this example, we first select the video and the play button elements from the HTML. We added an event listener on the play button, when the user clicks on the play button, we set the source of the video to the data-src and remove the data-src attribute. Then we call the play method on the video element to start the video and hide the play button.

This way the video will be loaded only when the user clicks the play button and not when the page loads.

You can also use this technique with other HTML5 media elements such as audio as well.

It's also worth noting that it's a good idea to provide a placeholder or a poster image for the video, so that users can see something on the page while the video is loading.

Lazy Loading Iframe Example

Here's an example of how you might use lazy loading to load an iframe in JavaScript:


<div class="iframe-container"> 
 <iframe class="lazy-load" data-src="https://example.com"></iframe> 
 <button class="load-button">Load</button> 
</div> 

var iframeContainer = document.querySelector('.iframe-container'); 
var iframe = document.querySelector('.lazy-load'); 
var loadButton = document.querySelector('.load-button'); 
loadButton.addEventListener('click', function() { 
 // set the source of the iframe to the data-src 
 iframe.src = iframe.getAttribute('data-src'); 
 // Remove the data-src attribute 
 iframe.removeAttribute('data-src'); 
 // Hide the load button 
 loadButton.style.display = 'none'; 
}); 

In this example, we first select the iframe element and the load button from the HTML. We added an event listener on the load button, when the user clicks on the load button, we set the source of the iframe to the data-src and remove the data-src attribute. Then we hide the load button.

This way the iframe will be loaded only when the user clicks the load button and not when the page loads.

It's also important to note that if you are loading an external site in the iframe, you should ensure that you have the appropriate permissions and that you are not violating any terms of service.

You can also use this technique with other HTML elements such as audio, video and images as well.

Lazy Loading Content on Scroll

Here's an example of how you might use lazy loading to load content as the user scrolls in JavaScript:


<div class="content-container"> 
 <div class="content lazy-load" data-src="content1.html"></div> 
 <div class="content lazy-load" data-src="content2.html"></div> 
 <div class="content lazy-load" data-src="content3.html"></div> 
</div> 

// Get all the content with the lazy-load class 
var contents = document.querySelectorAll('.lazy-load'); 
// Create a function to load content 
function loadContent(content) { 
 // Get the data-src attribute 
 var src = content.getAttribute('data-src'); 
 // Create an XHR object 
 var xhr = new XMLHttpRequest(); 
 // Open the request 
 xhr.open('GET', src); 
 // Send the request 
 xhr.send(); 
 // On load 
 xhr.onload = function() { 
 if (xhr.status === 200) { 
 // Set the innerHTML of the content to the response 
 content.innerHTML = xhr.response; 
 } 
 }; 
} 
// Listen for the scroll event 
window.addEventListener('scroll', function() { 
 // Loop through each content 
 contents.forEach(function(content) { 
 // Get the rect of the content 
 var rect = content.getBoundingClientRect(); 
 // If the content is in the viewport 
 if (rect.top < window.innerHeight && rect.bottom > 0) { 
 // Load the content 
 loadContent(content); 
 // Remove the lazy-load class 
 content.classList.remove('lazy-load'); 
 } 
 }); 
}); 

In this example, we're using the scroll event to detect when a content comes into the viewport. We first select all the contents with the class lazy-load and then add an event listener on the scroll event. On each scroll event, we loop through each content, check if it's in the viewport by checking the position of the content by using getBoundingClientRect() function and then use an XHR object to load the content asynchronously. Once the content is loaded, we set the innerHTML of the content to the response and remove the lazy-load class.

This way the browser will only load contents that are visible in the viewport and the others will be loaded when they scroll into the viewport.

You can also use a library like Waypoints which provides a simple API for triggering a function when an element is scrolled into view.

Lazy Loading and CDN

Lazy loading can be used in conjunction with a Content Delivery Network (CDN) to improve the performance of a website. A CDN is a network of servers that are distributed around the world, and are used to deliver content to users based on their geographic location.

When a user requests a resource from a website that is using a CDN, the CDN will determine the user's location and then serve the resource from the server that is closest to the user. This can significantly reduce the amount of time it takes for a resource to be delivered to the user.

By using lazy loading in conjunction with a CDN, you can ensure that only the resources that are needed by the user are loaded, and that they are loaded from the server that is closest to the user. This can help to improve the performance of your website by reducing the amount of time it takes for resources to be loaded, as well as reducing the amount of bandwidth that is used.

It's also worth noting that many CDN providers offer their own libraries or modules for lazy loading, so you may want to check if your CDN provider offers such a library, and if so, use it.

In summary, lazy loading and CDN are complementary concepts. Lazy loading allows you to load only the resources that are needed by the user, while CDN allows you to deliver those resources to the user as quickly as possible. Together they can help to significantly improve the performance of your website and provide a better user experience.