無論 `display:none`、`visibility:hidden`、還是 `opacity:0`、`width:0`、`height:0`,只要 `` 元素存在於 DOM 中且 `src` 屬性有值,瀏覽器**一定會發起網路請求下載圖片**。
// 1. 開發者工具 Network 面板
// 勾選 "Disable cache",刷新頁面,觀察 img 請求狀態
// 2. JavaScript 動態驗證
const img = document.createElement('img');
img.style.display = 'none';
img.src = '/test.jpg';
document.body.appendChild(img);
// 在 Network 面板即可看到請求已發出
// 移除元素後請求可能繼續(取決於瀏覽器實現)
| 方法 | 原理 | 適用場景 |
|---|---|---|
| 不設置 `src` 屬性 | 無請求觸發源 | 懶加載、條件加載 |
| `loading="lazy"` (HTML 標準) | 瀏覽器原生延遲加載,視口外不請求 | 長列表、首屏優化 |
| IntersectionObserver 手動懶加載 | 進入視口時動態設定 `src` | 需兼容舊瀏覽器、自定義閾值 |
| CSS `content` 背景圖替代 | 非 ` |
裝飾性圖標、圖片 |
| ` |
響應式圖片,條件匹配才請求 | 多尺寸適配 |
<!-- 原生懶加載,支援 Chrome 76+, Firefox 75+, Edge 79+ -->
<img src="real-image.jpg" loading="lazy" alt="描述" width="800" height="600">
<!-- 兼容方案:data-src + IntersectionObserver -->
<img data-src="real-image.jpg" class="lazy-img" alt="描述">
<script>
if ('IntersectionObserver' in window) {
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src;
img.classList.remove('lazy-img');
observer.unobserve(img);
}
});
}, { rootMargin: '100px' }); // 提前 100px 觸發
document.querySelectorAll('.lazy-img').forEach(img => observer.observe(img));
} else {
// 降級:直接加載
document.querySelectorAll('.lazy-img').forEach(img => {
img.src = img.dataset.src;
});
}
</script>
CSS 可見性屬性**不影響**瀏覽器的資源獲取邏輯。控制圖片加載的唯一正確手段是**控制 `src` 屬性的設置時機**。優先使用原生 `loading="lazy"`,舊環境配合 `IntersectionObserver` 實現真正的按需加載。