目錄
What Is the Intersection Observer API?
Lazy Loading Images with Intersection Observer
Beyond Images: Lazy Load Components or Ads
Trigger Animations on Scroll
Performance Tips and Caveats
Final Thoughts
首頁 web前端 H5教程 使用交叉點觀察者API進行懶惰加載和更多

使用交叉點觀察者API進行懶惰加載和更多

Jul 31, 2025 am 09:20 AM

使用 Intersection Observer API 可高效实现懒加载,相比传统方法性能更优;2. 通过设置 data-src 标记图片占位,利用 observer 监听元素进入视口时加载真实资源;3. 可扩展至懒加载组件、广告或评论区,减少首屏负载;4. 结合 rootMargin 预加载临界内容,提升用户体验;5. 动画触发同样适用,元素可见时再播放,避免滚动卡顿;6. 注意避免监听过多元素,及时调用 unobserve() 释放资源;7. 对不支持的旧浏览器需引入 polyfill。该 API 让浏览器自动处理可见性检测,显著提升页面性能与交互流畅度。

Lazy loading images and content has become a standard optimization technique for improving page performance and user experience. One of the most efficient and modern ways to implement this is by using the Intersection Observer API. Unlike older methods that relied on scroll event listeners and getBoundingClientRect(), Intersection Observer offers a more performant and cleaner approach by asynchronously monitoring when elements enter or exit the viewport.

Here’s how you can use it for lazy loading—and a few other practical use cases.


What Is the Intersection Observer API?

The Intersection Observer API lets you watch changes in the visibility of a target element relative to a root element (usually the viewport). Instead of manually calculating positions on scroll—a performance-heavy operation—you define a callback that fires when an observed element intersects with the root at a specified threshold.

This makes it ideal for:

  • Lazy loading images or content
  • Triggering animations when elements come into view
  • Implementing "infinite scroll"
  • Tracking ad or component visibility for analytics

Lazy Loading Images with Intersection Observer

Instead of loading all images on page load, you can defer loading offscreen images until they’re about to appear.

Step 1: Mark images with a placeholder

<img class="lazy lazy"  src="/static/imghw/default1.png"  data-src="path/to/actual-image.jpg"  
  data- 
  alt="Lazy loaded image"
>

Step 2: Set up the observer

const images = document.querySelectorAll('.lazy');

const imageObserver = new IntersectionObserver((entries, observer) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      const img = entry.target;
      const src = img.dataset.src;

      img.src = src;
      img.classList.remove('lazy');

      // Stop observing once loaded
      observer.unobserve(img);
    }
  });
}, {
  rootMargin: '50px'  // Start loading 50px before entering viewport
});

// Observe all lazy images
images.forEach(img => imageObserver.observe(img));

Key points:

  • rootMargin adds a buffer zone so images load just before they’re visible—avoiding blank gaps.
  • Once an image is loaded, unobserve() removes it from monitoring, reducing overhead.
  • Use low-quality placeholders or blur-up techniques for better UX.

Beyond Images: Lazy Load Components or Ads

You can lazy load entire DOM components, like embedded videos, comments sections, or third-party ads.

<div class="lazy-component" data-component="comments"></div>
const lazyComponents = document.querySelectorAll('.lazy-component');

const componentObserver = new IntersectionObserver((entries, observer) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      const container = entry.target;
      const component = container.dataset.component;

      if (component === 'comments') {
        loadComments(container);  // Your async loading function
      }

      observer.unobserve(container);
    }
  });
});

lazyComponents.forEach(el => componentObserver.observe(el));

This reduces initial page weight and avoids loading heavy scripts until necessary.


Trigger Animations on Scroll

Intersection Observer is perfect for animating elements as they enter the viewport.

.animate {
  opacity: 0;
  transform: translateY(20px);
  transition: opacity 0.5s, transform 0.5s;
}

.animate.visible {
  opacity: 1;
  transform: translateY(0);
}
const animateElements = document.querySelectorAll('.animate');

const fadeObserver = new IntersectionObserver((entries) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      entry.target.classList.add('visible');
      // Optionally stop observing after animation
      fadeObserver.unobserve(entry.target);
    }
  });
}, { threshold: 0.1 }); // Trigger when 10% of element is visible

animateElements.forEach(el => fadeObserver.observe(el));

This avoids janky scroll handlers and ensures animations only run when needed.


Performance Tips and Caveats

  • Avoid observing too many elements: If you have hundreds of items, consider throttling or using virtualization.
  • Use rootMargin strategically: Preload content slightly before it's visible to prevent delays.
  • Fallback for older browsers: Intersection Observer isn’t supported in IE. Use a polyfill like intersection-observer if needed.
  • Don’t forget unobserve(): Clean up after loading to prevent memory leaks and unnecessary checks.

Final Thoughts

The Intersection Observer API simplifies visibility detection and makes lazy loading straightforward and performant. Whether you're optimizing images, deferring component rendering, or enhancing scroll-driven interactions, it’s a powerful tool that should be in every modern web developer’s toolkit.

Basically: let the browser handle the heavy lifting, and focus on what matters—better performance and smoother UX.

以上是使用交叉點觀察者API進行懶惰加載和更多的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

HTML5解析器如何處理錯誤? HTML5解析器如何處理錯誤? Aug 02, 2025 am 07:51 AM

HTML5parsershandlemalformedHTMLbyfollowingadeterministicalgorithmtoensureconsistentandrobustrendering.1.Formismatchedorunclosedtags,theparserautomaticallyclosestagsandadjustsnestingbasedoncontext,suchasclosingabeforeaandreopeningitafterward.2.Withimp

什麼是HTML5數據屬性? 什麼是HTML5數據屬性? Aug 06, 2025 pm 05:39 PM

HTML5dataattributesarecustom,validHTMLattributesusedtostoreextrainformationinelementsforJavaScriptorCSS.1.Theyaredefinedasdata-*attributes,likedata-user-id="123".2.Theyallowembeddingprivate,customdatadirectlyinmarkupwithoutaffectinglayoutor

HTML5中的局部元素是什麼? HTML5中的局部元素是什麼? Aug 12, 2025 pm 04:37 PM

thelementshouldshouldsbousedforcontenttangentytothemaincontent,SustAssidebars,pullquotes,定義,廣告,orrelelatedLinks; 2. ItcanbeplectlaceDinSideSideRoutsIdeAnartIcleDeAlticleDepledePonconTeptOncontendementement; 3.Seasemanticemanticelementthatenhancesacaccccccccccccccccceedibilityancibilityandseobypyandseobyp.Anderancebyp.And.anceScebibilibilyandseobyp

如何處理HTML5畫布上的鼠標事件? 如何處理HTML5畫布上的鼠標事件? Aug 02, 2025 am 06:29 AM

要正確處理HTML5canvas上的鼠標事件,首先需給canvas添加事件監聽器,然後計算鼠標相對於canvas的坐標,接著通過幾何檢測判斷是否與繪製的對象交互,最後實現如拖拽等交互模式。 1.使用addEventListener為canvas綁定mousedown、mousemove、mouseup和mouseleave事件;2.利用getBoundingClientRect方法將clientX/clientY轉換為相對於canvas的坐標;3.通過手動幾何計算(如矩形邊界或圓的距離公式)檢測鼠

如何在HTML5中依次播放多個音頻文件? 如何在HTML5中依次播放多個音頻文件? Aug 25, 2025 pm 03:08 PM

可以通過監聽HTML5音頻元素的ended事件來依次播放多個音頻文件,首先明確答案是使用ended事件觸發下一個音頻播放;具體步驟為:1.定義音頻文件數組並獲取audio元素;2.設置當前播放索引,加載並播放首個音頻;3.為audio元素綁定ended事件,在事件觸發時遞增索引並加載下一個音頻;4.可選擇實現循環播放或播放結束後停止;5.可預加載下一個音頻以提升體驗;6.添加錯誤處理以跳過失敗的音頻;7.注意瀏覽器autoplay限制,需由用戶交互觸發首次播放,確保後續播放不被阻止,整個過程通過

HTML5中的可讀性屬性是什麼? HTML5中的可讀性屬性是什麼? Aug 08, 2025 am 11:55 AM

ThereadonlyattributeinHTML5makesforminputsnon-editablewhilestillallowingsubmissionanduserinteraction;1.Itappliestoandelements;2.Itisabooleanattribute,soonly"readonly"needstobepresent;3.Unlike"disabled",itallowsfocusandthedataisinc

HTML5中支持的音頻格式是什麼? HTML5中支持的音頻格式是什麼? Aug 05, 2025 pm 08:29 PM

HTML5音頻格式支持因瀏覽器而異,最常用格式包括:1.MP3(.mp3,audio/mpeg,所有主流瀏覽器均支持,兼容性最佳);2.WAV(.wav,audio/wav,支持較好但文件大,適合短音頻);3.OGG(.ogg/.oga,audio/ogg,Chrome、Firefox、Opera支持,Safari和IE不支持,開源免費);4.AAC(.aac/.m4a,audio/aac,Safari、Chrome、Edge支持,Firefox支持有限,常用於蘋果設備)。為確保兼容性,應在標籤

如何創建簡單的HTML5網頁 如何創建簡單的HTML5網頁 Aug 12, 2025 am 11:51 AM

創建一個簡單的HTML5網頁需要先使用聲明文檔類型,接著構建包含、和的基本結構,其中內設置字符編碼、視口和標題,內添加可見內容如標題、段落、鏈接、圖片和列表,保存為.html文件後即可在瀏覽器中直接打開查看,無需服務器支持,這是一個完整且有效的HTML5頁面的基礎。

See all articles