By using this site, you agree to the Privacy Policy and Terms of Use.
Accept
World of SoftwareWorld of SoftwareWorld of Software
  • News
  • Software
  • Mobile
  • Computing
  • Gaming
  • Videos
  • More
    • Gadget
    • Web Stories
    • Trending
    • Press Release
Search
  • Privacy
  • Terms
  • Advertise
  • Contact
Copyright © All Rights Reserved. World of Software.
Reading: How to Implement Lazy Loading Images and Videos in JavaScript | HackerNoon
Share
Sign In
Notification Show More
Font ResizerAa
World of SoftwareWorld of Software
Font ResizerAa
  • Software
  • Mobile
  • Computing
  • Gadget
  • Gaming
  • Videos
Search
  • News
  • Software
  • Mobile
  • Computing
  • Gaming
  • Videos
  • More
    • Gadget
    • Web Stories
    • Trending
    • Press Release
Have an existing account? Sign In
Follow US
  • Privacy
  • Terms
  • Advertise
  • Contact
Copyright © All Rights Reserved. World of Software.
World of Software > Computing > How to Implement Lazy Loading Images and Videos in JavaScript | HackerNoon
Computing

How to Implement Lazy Loading Images and Videos in JavaScript | HackerNoon

News Room
Last updated: 2025/09/21 at 8:31 PM
News Room Published 21 September 2025
Share
SHARE

Website performance has become a critical ranking factor for search engines and a key driver of user experience. When a site loads slowly, visitors are more likely to leave before engaging with the content. One of the biggest culprits behind sluggish websites is heavy media – especially images and videos. Fortunately, lazy loading provides an efficient way to improve page speed without sacrificing visual quality.

In this article, we’ll explore what lazy loading is, why it matters, and how you can implement it for images and videos using JavaScript.

What Is Lazy Loading?

Lazy loading is a web optimization technique that delays the loading of non-critical resources until they are actually needed. Instead of loading all images and videos at once during the initial page load, lazy loading only fetches them when they appear in (or near) the user’s viewport.

For example, if your page has 20 images but only 3 are visible when the visitor first lands on the page, lazy loading ensures that only those 3 images are loaded initially. The rest are downloaded only when the user scrolls down.

The result? Faster load times, reduced bandwidth usage, and a smoother browsing experience.

Native Lazy Loading With HTML

Before diving into JavaScript, it’s worth mentioning that modern browsers support a native lazy loading attribute for images and iframes.

<img src="image.jpg" alt="Example" loading="lazy">
<iframe src="video.html" loading="lazy"></iframe>

This is the easiest solution because it requires no extra code. However, not all browsers fully support it, and it may lack customization options. That’s where JavaScript comes in.

Lazy Loading Images With JavaScript

One of the most reliable ways to implement lazy loading is with the Intersection Observer API. This API lets you detect when elements enter or exit the viewport, making it ideal for conditional loading of resources.

Step 1: Update Your HTML

Instead of placing the image URL in the src attribute, you store it in a data-src attribute.

<img data-src="image.jpg" alt="Lazy loaded example" class="lazy-image">

Step 2: Add JavaScript Code

document.addEventListener("DOMContentLoaded", function () {
&nbsp;&nbsp;const lazyImages = document.querySelectorAll("img.lazy-image");
&nbsp;&nbsp;const imageObserver = new IntersectionObserver((entries, observer) => {
&nbsp;&nbsp;&nbsp;&nbsp;entries.forEach(entry => {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if (entry.isIntersecting) {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;const img = entry.target;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;img.src = img.dataset.src;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;img.classList.remove("lazy-image");
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;observer.unobserve(img);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;&nbsp;&nbsp;});
&nbsp;&nbsp;});
&nbsp;&nbsp;lazyImages.forEach(img => {
&nbsp;&nbsp;&nbsp;&nbsp;imageObserver.observe(img);
&nbsp;&nbsp;});
});

Here’s what happens:

  • The script looks for all images with the class lazy-image.
  • When an image scrolls into view, its data-src is transferred into src.
  • The observer then stops tracking that image.

Lazy Loading Videos With JavaScript

Videos and embedded iframes (like YouTube) are even heavier than images, making them prime candidates for lazy loading.

Step 1: Update Your HTML

<iframe data-src="https://www.youtube.com/embed/VIDEO_ID"&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;class="lazy-video"&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;width="560" height="315"&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;frameborder="0" allowfullscreen></iframe>

Notice that the src attribute has been replaced by data-src.

Step 2: Add JavaScript Code

document.addEventListener("DOMContentLoaded", function () {
&nbsp;&nbsp;const lazyVideos = document.querySelectorAll("iframe.lazy-video");
&nbsp;&nbsp;const videoObserver = new IntersectionObserver((entries, observer) => {
&nbsp;&nbsp;&nbsp;&nbsp;entries.forEach(entry => {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if (entry.isIntersecting) {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;const video = entry.target;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;video.src = video.dataset.src;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;video.classList.remove("lazy-video");
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;observer.unobserve(video);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;&nbsp;&nbsp;});
&nbsp;&nbsp;});
&nbsp;&nbsp;lazyVideos.forEach(video => {
&nbsp;&nbsp;&nbsp;&nbsp;videoObserver.observe(video);
&nbsp;&nbsp;});
});

When the user scrolls near the video, the actual YouTube (or Vimeo) URL is loaded, saving precious loading time.

Fallback for Older Browsers

If you need to support older browsers that don’t have the Intersection Observer API, you can fall back to using the scroll event:

function lazyLoad() {
&nbsp;&nbsp;const lazyElements = document.querySelectorAll("[data-src]");
&nbsp;&nbsp;lazyElements.forEach(el => {
&nbsp;&nbsp;&nbsp;&nbsp;if (el.getBoundingClientRect().top < window.innerHeight + 200) {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;el.src = el.dataset.src;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;el.removeAttribute("data-src");
&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;});
}
window.addEventListener("scroll", lazyLoad);
window.addEventListener("resize", lazyLoad);
window.addEventListener("orientationchange", lazyLoad);

This checks the element’s position relative to the viewport and loads it when it’s close to being visible.

Best Practices for Lazy Loading

  • Do not lazy load above-the-fold images: These should load instantly to avoid delays in the initial render.
  • Combine with modern image formats: Use WebP or AVIF for smaller file sizes.
  • Test with performance tools: Google PageSpeed Insights and Lighthouse can help you measure improvements.
  • Provide placeholders: Use a small blurred image or a loading animation to prevent layout shifts.

Tip: Optimizing user experience doesn’t stop with media. Even small enhancements, like interactive maps, can make a difference. For a more detailed guide on image loading techniques, you can check out this resource.

SEO and User Experience Benefits

Beyond performance, lazy loading can also improve your site’s SEO and engagement metrics. Since Google now considers page speed and Core Web Vitals as ranking factors, reducing unnecessary resource loading gives your site a better chance at ranking higher in search results.

At the same time, users benefit from a faster, smoother browsing experience, which reduces bounce rates and encourages them to stay longer on your site. In short, lazy loading is not just a technical improvement—it’s a competitive advantage.

Conclusion

Lazy loading is one of the simplest yet most effective techniques for improving website speed and user experience. By implementing lazy loading for images and videos using JavaScript, you reduce initial page load time, save bandwidth, and create a smoother browsing experience for your visitors.

Whether you rely on native HTML attributes or a JavaScript-based approach, this optimization is a must-have for modern web development.

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Share This Article
Facebook Twitter Email Print
Share
What do you think?
Love0
Sad0
Happy0
Sleepy0
Angry0
Dead0
Wink0
Previous Article How Do Black Holes Form? This New Study Offers An Answer – BGR
Next Article The iPhone 17 has officially landed. Here’s how and when you can preorder all 4 phones.
Leave a comment

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Stay Connected

248.1k Like
69.1k Follow
134k Pin
54.3k Follow

Latest News

How to Celebrate AAPI Heritage Month on Social Media |
Computing
Google’s Home app finally gets a Gemini-infused redesign
Gadget
With Amazon And Salesforce As Customers, Agentic AI Startup AppZen Lands $180M To ‘Transform’ Finance Teams
News
Replit Introduces Agent 3 for Extended Autonomous Coding and Automation
News

You Might also Like

Computing

How to Celebrate AAPI Heritage Month on Social Media |

7 Min Read
Computing

The Ruthless Logic of Scarcity: How Marketers Weaponize Desire in the Attention Economy | HackerNoon

8 Min Read
Computing

⚡ Weekly Recap: Chrome 0-Day, AI Hacking Tools, DDR5 Bit-Flips, npm Worm & More

48 Min Read
Computing

A Major Trading Firm Has Open-Sourced The Latest Linux File-System: TernFS

2 Min Read
//

World of Software is your one-stop website for the latest tech news and updates, follow us now to get the news that matters to you.

Quick Link

  • Privacy Policy
  • Terms of use
  • Advertise
  • Contact

Topics

  • Computing
  • Software
  • Press Release
  • Trending

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

World of SoftwareWorld of Software
Follow US
Copyright © All Rights Reserved. World of Software.
Welcome Back!

Sign in to your account

Lost your password?