/js/lazyload/
├─ grey.gif # 佔位圖(1×1px 透明或灰色)
├─ jquery.js # jQuery 核心庫
└─ jquery.lazyload.js # LazyLoad 插件
<head>
<script src="/js/lazyload/jquery.js"></script>
<script src="/js/lazyload/jquery.lazyload.js"></script>
</head>
<!-- 原圖網址放在 data-original,src 指向佔位圖 -->
<img class="lazy" data-original="real-image.jpg" src="/js/lazyload/grey.gif" alt="描述" />
$(function() {
$("img.lazy").lazyload({
effect: "fadeIn", // 淡入效果:show | fadeIn | slideDown
threshold: 200, // 提前 200px 開始載入
event: "scroll", // 觸發事件:scroll | click | mouseover
container: window, // 滾動容器,預設 window
failure_limit: 10, // 容錯:HTML 混亂時多載入幾張
placeholder: "grey.gif", // 佔位圖(已在 src 指定可省略)
skip_invisible: true // 跳過隱藏圖片(display:none)
});
});
| 參數 | 類型 | 預設值 | 說明 |
|---|---|---|---|
threshold | Number | 0 | 提前載入距離(像素),正值=提前,負值=延後 |
effect | String | "show" | 顯示動畫:show/fadeIn/slideDown/custom function |
event | String | "scroll" | 觸發方式:scroll/click/mouseover/自訂事件 |
container | jQuery/Element | window | 指定滾動容器(如側邊欄、Modal 內部捲軸) |
failure_limit | Number | 0 | HTML 結構亂序時,多檢查幾張不可見區域圖片 |
data_attribute | String | "original" | 自訂資料屬性名(data-src、data-lazy 等) |
appear | Function | null | 圖片出現時回調 |
load | Function | null | 圖片載入完成回調 |
HTML 標準屬性,零依賴、零 JS、瀏覽器原生最佳化:
<img src="photo.jpg" loading="lazy" alt="描述" width="800" height="600" />
<iframe src="video.html" loading="lazy"></iframe>
| 瀏覽器 | loading="lazy" | IntersectionObserver |
|---|---|---|
| Chrome 76+ | ✅ | ✅ |
| Firefox 75+ | ✅ | ✅ |
| Safari 15.4+ | ✅ | ✅ |
| Edge 79+ | ✅ | ✅ |
| IE | ❌ | ❌ (需 Polyfill) |
需支援 IE 或要精細控制載入邏輯時使用:
const observer = new IntersectionObserver((entries, obs) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src;
img.onload = () => img.classList.add('loaded');
obs.unobserve(img);
}
});
}, {
rootMargin: '200px 0px', // 相當於 threshold 200px
threshold: 0.01
});
document.querySelectorAll('img[data-src]').forEach(img => observer.observe(img));
aspect-ratio,防止佈局位移 (CLS)loading="eager"srcset + sizes 提供響應式圖片loading="lazy" + IntersectionObserver Polyfill