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.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.

How to Implement Lazy Loading Images and Videos in JavaScript

2025/09/22 01:30

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.

Disclaimer: The articles reposted on this site are sourced from public platforms and are provided for informational purposes only. They do not necessarily reflect the views of MEXC. All rights remain with the original authors. If you believe any content infringes on third-party rights, please contact service@support.mexc.com for removal. MEXC makes no guarantees regarding the accuracy, completeness, or timeliness of the content and is not responsible for any actions taken based on the information provided. The content does not constitute financial, legal, or other professional advice, nor should it be considered a recommendation or endorsement by MEXC.
Share Insights

You May Also Like

CME Group to launch options on XRP and SOL futures

CME Group to launch options on XRP and SOL futures

The post CME Group to launch options on XRP and SOL futures appeared on BitcoinEthereumNews.com. CME Group will offer options based on the derivative markets on Solana (SOL) and XRP. The new markets will open on October 13, after regulatory approval.  CME Group will expand its crypto products with options on the futures markets of Solana (SOL) and XRP. The futures market will start on October 13, after regulatory review and approval.  The options will allow the trading of MicroSol, XRP, and MicroXRP futures, with expiry dates available every business day, monthly, and quarterly. The new products will be added to the existing BTC and ETH options markets. ‘The launch of these options contracts builds on the significant growth and increasing liquidity we have seen across our suite of Solana and XRP futures,’ said Giovanni Vicioso, CME Group Global Head of Cryptocurrency Products. The options contracts will have two main sizes, tracking the futures contracts. The new market will be suitable for sophisticated institutional traders, as well as active individual traders. The addition of options markets singles out XRP and SOL as liquid enough to offer the potential to bet on a market direction.  The options on futures arrive a few months after the launch of SOL futures. Both SOL and XRP had peak volumes in August, though XRP activity has slowed down in September. XRP and SOL options to tap both institutions and active traders Crypto options are one of the indicators of market attitudes, with XRP and SOL receiving a new way to gauge sentiment. The contracts will be supported by the Cumberland team.  ‘As one of the biggest liquidity providers in the ecosystem, the Cumberland team is excited to support CME Group’s continued expansion of crypto offerings,’ said Roman Makarov, Head of Cumberland Options Trading at DRW. ‘The launch of options on Solana and XRP futures is the latest example of the…
Share
BitcoinEthereumNews2025/09/18 00:56
Share
Digital Asset Treasury Raises $20 Billion, Focus Shifts

Digital Asset Treasury Raises $20 Billion, Focus Shifts

The post Digital Asset Treasury Raises $20 Billion, Focus Shifts appeared on BitcoinEthereumNews.com. Key Points: DAT raises $20B in 2023, evolving market focus. Institutional focus on execution, M&A heightens. Crypto startup funding faces crowding-out impact. Digital Asset Treasury has secured over $20 billion in funding this year, indicating a strategic shift in the cryptocurrency sector. Institutional investors focus on mergers and acquisitions, impacting traditional crypto startups with constrained funding and smaller upcoming projects. $20B Treasury Inflows Spur Strategic Market Shifts The Digital Asset Treasury has accrued over $20 billion this year, significantly impacting the landscape. Institutional investors are steering attention from high-value premiums to execution, mergers, and acquisition strategies. These activities are reshaping conventional crypto startup financing, noted ChainCatcher, with major players adopting refined approaches. This strategic pivot is causing immediate effects. Traditional crypto startup financing is increasingly crowded out, as revealed by industry sources. Further project launches are anticipated early next year, though their scales are predicted to be smaller, highlighting a shift towards tactical capital allocation. Reactions within the cryptocurrency community echo these changes. Joseph Chalom expressed his enduring belief in Ethereum’s long-term potential, noting, “My focus has always been on building a bridge between traditional finance and digital assets while upholding my principles and raising industry standards… I chose to return because of my firm belief in the long-term opportunities of Ethereum.” Additionally, key executives like Weng Xiaoqi have voiced pivotal sentiments about the Digital Assets industry. Institutional KOLs, including Liang Xinjun’s appointment at Yunfeng Financial, have underscored this trajectory towards execution and substantial capital-horizontal integrations in Asian markets. Historical Patterns Echo as Ethereum Faces Volatility Did you know? In past crypto cycles, 2021 and 2017 notably, rounds exceeding $500 million peaked as sectors saturated. Currently, funding strategies are realigning to focus on high-market-cap assets, showcasing cyclical financial shifts. Data from CoinMarketCap shows Ethereum (ETH) currently trades at $4,377.29, with…
Share
BitcoinEthereumNews2025/09/22 08:41
Share