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.

ข้อจำกัดความรับผิดชอบ: บทความที่โพสต์ซ้ำในไซต์นี้มาจากแพลตฟอร์มสาธารณะและมีไว้เพื่อจุดประสงค์ในการให้ข้อมูลเท่านั้น ซึ่งไม่ได้สะท้อนถึงมุมมองของ MEXC แต่อย่างใด ลิขสิทธิ์ทั้งหมดยังคงเป็นของผู้เขียนดั้งเดิม หากคุณเชื่อว่าเนื้อหาใดละเมิดสิทธิของบุคคลที่สาม โปรดติดต่อ service@mexc.com เพื่อลบออก MEXC ไม่รับประกันความถูกต้อง ความสมบูรณ์ หรือความทันเวลาของเนื้อหาใดๆ และไม่รับผิดชอบต่อการดำเนินการใดๆ ที่เกิดขึ้นตามข้อมูลที่ให้มา เนื้อหานี้ไม่ถือเป็นคำแนะนำทางการเงิน กฎหมาย หรือคำแนะนำจากผู้เชี่ยวชาญอื่นๆ และไม่ถือว่าเป็นคำแนะนำหรือการรับรองจาก MEXC
แชร์ข้อมูลเชิงลึก

คุณอาจชอบเช่นกัน

MAGACOIN Presale Hits $14M | Shiba Inu SHIB ICO Comparison

MAGACOIN Presale Hits $14M | Shiba Inu SHIB ICO Comparison

The post MAGACOIN Presale Hits $14M | Shiba Inu SHIB ICO Comparison appeared on BitcoinEthereumNews.com. The presale of MAGACOIN FINANCE has now crossed $14 million, sparking comparisons with the early days of Shiba Inu. Analysts argue that just as SHIB’s initial momentum led to historic highs, MAGACOIN FINANCE could follow a similar trajectory, with hourly price increases and growing whale activity making it a hot topic. MAGACOIN Presale Frenzy Crosses $14 Million Momentum around MAGACOIN FINANCE has reached a tipping point. With over thousands investors already on board, the altcoin is outpacing expectations. It has seen investment of over $14 million amid the ongoing rush. Unlike many projects that dip after an initial wave, MAGACOIN has shown a one-way climb, fueling urgency among traders. The presale structure adds further fuel. Early buyers gain the advantage of an increasing price model, where tokens get more expensive as each stage passes. With whales already positioning ahead of exchange listings, retail investors are rushing to secure allocations before liquidity events drive valuations higher. For many, this is being labeled the best crypto to buy in 2025 as the window to catch it early narrows. Lessons From Shiba Inu ICO Days The comparison to Shiba Inu (SHIB) comes from history. When SHIB launched in mid-2020, its creator Ryoshi sent 505 trillion SHIB tokens — nearly half the supply — to Ethereum co-founder Vitalik Buterin. Buterin’s later decisions shaped SHIB’s story. He donated over 50 trillion SHIB (worth $1 billion) to India’s COVID-19 relief fund and burned 410 trillion SHIB tokens (valued at $6 billion at the time) by sending them to a dead address. This event created scarcity and helped push SHIB to its record high within months. Analysts now note that MAGACOIN FINANCE, with its fair launch and zero VC involvement, may be entering its own pivotal phase — echoing how SHIB went from obscurity to one of…
แชร์
BitcoinEthereumNews2025/09/22 10:07
แชร์
Hallmark Announces 2025 ‘Countdown To Christmas’ Dates, Movies, And Fan Events

Hallmark Announces 2025 ‘Countdown To Christmas’ Dates, Movies, And Fan Events

The post Hallmark Announces 2025 ‘Countdown To Christmas’ Dates, Movies, And Fan Events appeared on BitcoinEthereumNews.com. Laci J Mailey and Ashley Williams star in “An Alpine Holiday.” ©2025 Hallmark Media Hallmark has announced that this year their annual Countdown to Christmas will kick off on Friday, October 17th. Spanning across ten weeks, Hallmark is set to deliver nearly 80 hours of all-new programming, with original movies premiering every Saturday and Sunday night. A big event finds Hallmark teaming up with the National Football League for Holiday Touchdown: A Bills Love Story. Set against the backdrop of the unique, tight-knit community of fans known as the Bills Mafia, and celebrating the Bills final season at their iconic venue, Highmark Stadium, the movie includes Bills Head Coach Sean McDermott, Running Back Ray Davis, Safety Damar Hamlin, Offensive Tackle Dion Dawkins, Tight End Dawson Knox, Long Snapper Reid Ferguson, Defensive Tackle DeWayne Carter and Wide Receiver Joshua Palmer. Buffalo Bills legend Jim Kelly, former teammates Steve Tasker, Thurman Thomas, Scott Norwood and Andre Reed, along with Bills play-by-play announcer Chris Brown also appear. And paying homage to the late, great broadcast journalist and die-hard Bills fan Tim Russert, his son Luke Russert rounds out the team. Other new fare includes movies Tidings for the Season, An Alpine Holiday, She’s Making a List, A Suite Holiday Romance, and The Christmas Baby. Also airing during the season will be reality cooking series, Baked with Love, and the second season of Finding Mr. Christmas, Hallmark’s competition to find their next leading man. To mark the centennial of country music’s iconic venue, the Grand Ole Opry, Hallmark will present A Grand Ole Opry Christmas. Grammy-award winner and Opry Member Brad Paisley wrote and performs original music in the movie. He’s joined by other Opry members and country music artists Bill Anderson, Dailey & Vincent, Drew Baldridge, Jamey Johnson, Maggie Baugh, Megan Moroney, Mickey…
แชร์
BitcoinEthereumNews2025/09/18 01:38
แชร์