亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

目錄
How Intersection Observer Works
Step 1: Mark Elements for Lazy Loading
Step 2: Set Up the Intersection Observer
Key Benefits and Tips
Optional: Add Placeholder or Fade-In Effect
Browser Support & Fallback
首頁 web前端 H5教程 與交叉點(diǎn)觀察者API的懶惰加載圖像和iframe

與交叉點(diǎn)觀察者API的懶惰加載圖像和iframe

Aug 01, 2025 am 06:27 AM

使用Intersection Observer API可以高效實(shí)現(xiàn)圖片和iframe的懶加載,顯著提升頁面性能。 1. 使用data-src屬性標(biāo)記需懶加載的元素,避免初始加載;2. 創(chuàng)建Intersection Observer實(shí)例,通過rootMargin設(shè)置預(yù)加載距離,threshold定義觸發(fā)比例;3. 在回調(diào)中檢測元素可見性,將data-src賦值給src以加載內(nèi)容,并停止觀察該元素;4. 可添加CSS過渡實(shí)現(xiàn)平滑淡入效果;5. 對于不支持的瀏覽器,可使用polyfill或回退方案。此方法無需滾動監(jiān)聽,性能優(yōu)越,推薦在現(xiàn)代網(wǎng)頁中廣泛應(yīng)用。

Lazy loading images and iframes can significantly improve page performance by deferring the loading of off-screen content until it's about to enter the viewport. One of the most efficient and modern ways to implement this is using the Intersection Observer API , which eliminates the need for scroll event listeners and getBoundingClientRect() calls that can hurt performance.

Here's how you can use the Intersection Observer API to lazy load images and iframes.


How Intersection Observer Works

Instead of constantly checking an element's position during scroll (which can trigger expensive reflows), the Intersection Observer asynchronously notifies you when an observed element intersects with the viewport (or a container). This makes it ideal for lazy loading.

You define a callback that runs when visibility changes, and configure thresholds (eg, trigger when 10% of the element is visible).


Step 1: Mark Elements for Lazy Loading

Use data-src (or data-srcset for responsive images) to hold the real image or iframe URL. The browser won't load it until you assign it to src .

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

<!-- Lazy iframe -->
<iframe 
  data-src="https://example.com/embed" 
  class="lazy-iframe"
  frameborder="0"
></iframe>

Step 2: Set Up the Intersection Observer

 document.addEventListener("DOMContentLoaded", function () {
  const lazyImages = document.querySelectorAll("img.lazy");
  const lazyIframes = document.querySelectorAll("iframe.lazy-iframe");

  const observer = new IntersectionObserver((entries, observer) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        const element = entry.target;

        if (element.tagName === "IMG") {
          // Handle image
          if (element.dataset.src) {
            element.src = element.dataset.src;
            element.classList.remove("lazy");
            observer.unobserve(element);
          }
        }

        if (element.tagName === "IFRAME") {
          // Handle iframe
          if (element.dataset.src) {
            element.src = element.dataset.src;
            element.classList.remove("lazy-iframe");
            observer.unobserve(element);
          }
        }
      }
    });
  }, {
    rootMargin: "50px", // Start loading 50px before entering viewport
    threshold: 0.01 // Trigger when even 1% is visible
  });

  // Observe all lazy elements
  lazyImages.forEach(img => observer.observe(img));
  lazyIframes.forEach(iframe => observer.observe(iframe));
});

Key Benefits and Tips

  • Performance : No scroll event listeners, so no jank.
  • rootMargin : Use it to preload content slightly before it appears (eg, 50px ahead).
  • Threshold : Lower values (like 0.01 ) mean early triggering; higher values (like 1.0 ) wait until fully in view.
  • Remove observer : Once the src is set, unobserve the element to stop tracking.

Optional: Add Placeholder or Fade-In Effect

You can enhance UX by adding a low-quality placeholder or a fade-in transition:

 img.lazy {
  opacity: 0;
  transition: opacity 0.4s;
}

img:not(.lazy) {
  opacity: 1;
}

Now images will smoothly fade in after loading.


Browser Support & Fallback

Most modern browsers support Intersection Observer. For older ones (like IE), consider using a polyfill or fall back to scroll-based detection.

Alternatively, use the native loading="lazy" attribute for images and iframes — but note it doesn't work in all contexts or for dynamic iframes:

 <img src="/static/imghw/default1.png"  data-src="image.jpg"  class="lazy" loading="lazy" alt="與交叉點(diǎn)觀察者API的懶惰加載圖像和iframe">
<iframe src="https://example.com/embed" loading="lazy"></iframe>

However, Intersection Observer gives you more control , especially for complex layouts or when you need to handle custom logic.


Basically, using the Intersection Observer API is a clean, performant way to lazy load media. It's widely supported, easy to implement, and scales well across large pages.

以上是與交叉點(diǎn)觀察者API的懶惰加載圖像和iframe的詳細(xì)內(nèi)容。更多信息請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

本站聲明
本文內(nèi)容由網(wǎng)友自發(fā)貢獻(xiàn),版權(quán)歸原作者所有,本站不承擔(dān)相應(yīng)法律責(zé)任。如您發(fā)現(xiàn)有涉嫌抄襲侵權(quán)的內(nèi)容,請聯(lián)系admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費(fèi)脫衣服圖片

Undresser.AI Undress

Undresser.AI Undress

人工智能驅(qū)動的應(yīng)用程序,用于創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用于從照片中去除衣服的在線人工智能工具。

Clothoff.io

Clothoff.io

AI脫衣機(jī)

Video Face Swap

Video Face Swap

使用我們完全免費(fèi)的人工智能換臉工具輕松在任何視頻中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費(fèi)的代碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

功能強(qiáng)大的PHP集成開發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級代碼編輯軟件(SublimeText3)

熱門話題

Laravel 教程
1597
29
PHP教程
1488
72
使用HTML5拖放API添加阻力功能。 使用HTML5拖放API添加阻力功能。 Jul 05, 2025 am 02:43 AM

給網(wǎng)頁添加拖放功能的方法是使用HTML5的DragandDropAPI,它原生支持,無需額外庫。具體步驟如下:1.設(shè)置元素draggable="true"以啟用拖動;2.監(jiān)聽dragstart、dragover、drop和dragend事件;3.在dragstart中設(shè)置數(shù)據(jù),在dragover中阻止默認(rèn)行為,在drop中處理邏輯。此外,可通過appendChild實(shí)現(xiàn)元素移動,通過e.dataTransfer.files實(shí)現(xiàn)文件上傳。注意:必須調(diào)用preventDefaul

將ARIA屬性與HTML5語義元素用于可訪問性 將ARIA屬性與HTML5語義元素用于可訪問性 Jul 07, 2025 am 02:54 AM

需要同時使用ARIA和HTML5語義標(biāo)簽的原因是:HTML5語義元素雖自帶可訪問性含義,但ARIA能補(bǔ)足語義、增強(qiáng)輔助技術(shù)識別能力。例如舊版瀏覽器支持不足、無原生標(biāo)簽的組件(如模態(tài)框)、需動態(tài)更新狀態(tài)時,ARIA提供更細(xì)粒度控制。nav、main、aside等HTML5元素默認(rèn)對應(yīng)ARIArole,無需手動添加,除非需覆蓋默認(rèn)行為。應(yīng)加ARIA的情況包括:1.補(bǔ)充缺失的狀態(tài)信息,如用aria-expanded表示按鈕展開/收起狀態(tài);2.給非語義標(biāo)簽增加語義角色,如用div role實(shí)現(xiàn)選項(xiàng)卡并配

確保HTML5 Web應(yīng)用程序免受常見漏洞 確保HTML5 Web應(yīng)用程序免受常見漏洞 Jul 05, 2025 am 02:48 AM

前端開發(fā)中需重視HTML5應(yīng)用的安全隱患,主要包括XSS攻擊、接口安全及第三方庫風(fēng)險。1.防止XSS:對用戶輸入轉(zhuǎn)義,使用textContent、CSP頭、輸入驗(yàn)證,避免eval()和直接執(zhí)行JSON;2.保護(hù)接口:使用CSRFToken、SameSiteCookie策略、請求頻率限制、敏感信息加密傳輸;3.安全使用第三方庫:定期審計(jì)依賴、使用穩(wěn)定版本、減少外部資源、啟用SRI校驗(yàn),確保從開發(fā)初期就構(gòu)建安全防線。

將CSS和JavaScript與HTML5結(jié)構(gòu)有效整合。 將CSS和JavaScript與HTML5結(jié)構(gòu)有效整合。 Jul 12, 2025 am 03:01 AM

HTML5、CSS和JavaScript應(yīng)通過語義化標(biāo)簽、合理加載順序與解耦設(shè)計(jì)高效結(jié)合。1.使用HTML5語義化標(biāo)簽如、提升結(jié)構(gòu)清晰度與可維護(hù)性,利于SEO和無障礙訪問;2.CSS應(yīng)置于中,使用外部文件并按模塊拆分,避免內(nèi)聯(lián)樣式與延遲加載問題;3.JavaScript推薦放在前引入,使用defer或async異步加載以避免阻塞渲染;4.減少三者間強(qiáng)依賴,通過data-*屬性驅(qū)動行為、類名控制狀態(tài),統(tǒng)一命名規(guī)范提升協(xié)作效率。這些方法能有效優(yōu)化頁面性能與團(tuán)隊(duì)協(xié)作。

使用HTML5語義元素進(jìn)行頁面結(jié)構(gòu) 使用HTML5語義元素進(jìn)行頁面結(jié)構(gòu) Jul 07, 2025 am 02:53 AM

使用HTML5語義標(biāo)簽?zāi)芴嵘W(wǎng)頁結(jié)構(gòu)清晰度、可訪問性和SEO效果。1.語義標(biāo)簽如、、、、和使機(jī)器更易理解頁面內(nèi)容;2.各標(biāo)簽有明確用途:用于頂部區(qū)域,包裹導(dǎo)航鏈接,包含核心內(nèi)容,展示獨(dú)立文章,分組相關(guān)內(nèi)容,放置側(cè)邊欄,顯示底部信息;3.使用時需避免濫用、確保每頁僅一個、避免過度嵌套、合理使用和于區(qū)塊中。掌握這些要點(diǎn)能讓網(wǎng)頁結(jié)構(gòu)更規(guī)范且實(shí)用。

HTML5視頻不在Chrome中播放 HTML5視頻不在Chrome中播放 Jul 10, 2025 am 11:20 AM

HTML5視頻在Chrome中不播放的常見原因包括格式兼容性、自動播放策略、路徑或MIME類型錯誤以及瀏覽器擴(kuò)展干擾。1.視頻應(yīng)優(yōu)先使用MP4(H.264)格式,或提供多個標(biāo)簽適配不同瀏覽器;2.自動播放需添加muted屬性或通過用戶交互后用JavaScript觸發(fā).play();3.檢查文件路徑是否正確,并確保服務(wù)器配置了正確的MIME類型,本地測試建議使用開發(fā)服務(wù)器;4.廣告攔截插件或隱私模式可能阻止加載,可嘗試禁用插件、更換無痕窗口或更新瀏覽器版本以解決。

使用html5` `標(biāo)簽嵌入視頻內(nèi)容。 使用html5` `標(biāo)簽嵌入視頻內(nèi)容。 Jul 07, 2025 am 02:47 AM

使用HTML5的標(biāo)簽嵌入網(wǎng)頁視頻,支持多格式兼容、自定義控件和響應(yīng)式設(shè)計(jì)。1.基本用法:添加標(biāo)簽并設(shè)置src與controls屬性以實(shí)現(xiàn)播放功能;2.支持多格式:通過標(biāo)簽引入MP4、WebM、Ogg等不同格式提升瀏覽器兼容性;3.自定義外觀與行為:隱藏默認(rèn)控件并通過CSS與JavaScript實(shí)現(xiàn)樣式調(diào)整及交互邏輯;4.注意細(xì)節(jié):設(shè)置muted與autoplay實(shí)現(xiàn)自動播放,使用preload控制加載策略,結(jié)合width與max-width實(shí)現(xiàn)響應(yīng)式布局,利用添加字幕增強(qiáng)可訪問性。

使用HTML5畫布繪制圖形和動畫 使用HTML5畫布繪制圖形和動畫 Jul 05, 2025 am 01:09 AM

HTML5Canvas適合做網(wǎng)頁圖形和動畫,通過JavaScript操作上下文繪圖;①先在HTML添加canvas標(biāo)簽并獲取2D上下文;②使用fillRect、arc等方法繪制圖形;③動畫通過清空畫布、重繪、requestAnimationFrame循環(huán)實(shí)現(xiàn);④復(fù)雜功能需手動處理事件檢測、圖像繪制及對象封裝。

See all articles