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

Trump and Musk Reconcile at Charlie Kirk Memorial

Trump and Musk Reconcile at Charlie Kirk Memorial

The post Trump and Musk Reconcile at Charlie Kirk Memorial appeared on BitcoinEthereumNews.com. Key Points: Event rekindles past associations between Trump and Musk with political implications. High-profile gathering indicates reconciliation. No immediate crypto market impact observed post-event. Donald Trump and Elon Musk attended Charlie Kirk’s memorial in September 2025, shaking hands and exchanging brief words in New York City. Their public reconciliation could influence crypto markets, given Musk’s impact on digital asset prices and Trump’s historical role in crypto policy. Trump-Musk Reconciliation: High-Profile Memorial Meeting Donald Trump and Elon Musk attended the Charlie Kirk memorial service, where they sat together. The event was notable for their public appearance and reconciliation after a split in June. Attendees included prominent political figures such as Vice President JD Vance. The reunion signals a turning point in the relationship between Trump and Musk. Their prior disagreements had led to market speculation. This public interaction could influence perceptions of both leaders in the political and business arenas. Crypto Market Unmoved as DOGE Trades at $0.26 Did you know? Charlie Kirk played a pivotal role in bridging divides between influential figures, showcasing the power of diplomacy in politically-charged environments. According to CoinMarketCap, Dogecoin (DOGE) trades at $0.26, with a market cap of 39.45 billion USD, representing 0.98% market dominance. Its trading volume is 1.75 billion USD, with price changes of -2.25% in 24 hours and 58.66% over 90 days. Dogecoin(DOGE), daily chart, screenshot on CoinMarketCap at 23:35 UTC on September 21, 2025. Source: CoinMarketCap The Coincu research team suggests that the Musk-Trump interaction could set a precedence for other high-profile collaborations. These relationships can shape both the financial and technological landscapes, specifically influencing markets sensitive to Musk’s statements, as seen with Dogecoin in the past. DISCLAIMER: The information on this website is provided as general market commentary and does not constitute investment advice. We encourage you to do your own…
Share
BitcoinEthereumNews2025/09/22 07:42
Share
Hedera Price Maintains 0.24 Support While Setting Up for a Strong Upswing

Hedera Price Maintains 0.24 Support While Setting Up for a Strong Upswing

The post Hedera Price Maintains 0.24 Support While Setting Up for a Strong Upswing appeared on BitcoinEthereumNews.com. Hedera’s native token is drawing attention as analyst STEPH IS CRYPTO compares its 2020–2021 breakout with the current 2024–2025 market structure. The earlier cycle saw HBAR surge from under $0.01 to over $0.50 after months of accumulation. Today, the token is consolidating between $0.03 and $0.10, which Steph says could precede another multi-month bull run. Currently, HBAR trades at $0.24 with a market capitalization of $10.22 billion and a daily volume of $170.1 million, according to CryptoPulse. Analysts note key levels at $0.24 support and $0.244 resistance, eyeing a dip near $0.223 before a rebound toward $0.28–$0.30. Historical Pattern Suggests a New Expansion Phase Analyst STEPH compares Hedera’s current chart structure with its breakout cycle from 2020 to 2021. During that earlier period, the altcoin traded below $0.01 before surging above $0.50 after an extended base-building phase. The rally produced multiple new highs until a broad crypto market correction in 2022 ended the upward move. HBARUSDT Chart | Source:x The 2024–2025 setup shows similar characteristics. The asset has remained in a range between $0.03 and $0.10 for several months, creating a foundation that resembles the earlier accumulation phase. According to the analyst, repeating this structure may prepare it for another strong upward phase if overall market conditions and adoption remain favorable. Current Trading Range and Technical Structure Market data shows Hedera trading near $0.24, with a 0.38% gain over the last 24 hours. The 24-hour chart records price movements between $0.239 and $0.244, reflecting moderate intraday volatility. Trading volume stands at $170.1 million, and the network maintains a market capitalization of $10.22 billion with a circulating supply of about 42.39 billion, keeping it among the top 25 digital assets. HBAR 24-Hr Chart | Source: BraveNewCoin The intraday pattern included an early push toward $0.244, a pullback to $0.241, and a…
Share
BitcoinEthereumNews2025/09/22 07:02
Share