function checkBgImageLoad(url, callback) {
var img = new Image();
img.src = url;
// 關鍵:img.width > 0 表示瀏覽器已解碼成功 (可能來自快取)
if (img.width > 0) {
// 同步可用 (快取命中)
callback(true);
} else {
// 異步載入中,綁定事件
img.onload = function() {
callback(true);
cleanup();
};
img.onerror = function() {
callback(false);
cleanup();
};
}
function cleanup() {
img.onload = img.onerror = null;
img = null; // 釋放引用
}
}
// 使用
checkBgImageLoad('banner.jpg', function(ok) {
if (ok) {
document.body.style.backgroundImage = 'url(banner.jpg)';
} else {
console.warn('背景圖載入失敗,使用備用色');
document.body.style.backgroundColor = '#333';
}
});
new Image() 建立離屏圖片元素,設定 src 即啟動下載/解碼。img.width 立即可用 (>0),onload 可能同步觸發或不觸發。img.width === 0,需等待 onload/onerror 回調。img.complete 屬性也可判斷是否完成 (含錯誤),但 width > 0 更直觀區分成功/失敗。| 場景 | 表現 | 風險 |
|---|---|---|
| 圖片極大 (數 MB) | 下載慢,width 長時間為 0 | 誤判為失敗,若無 onload 等待會過早回調失敗 |
| 網路極慢/斷網 | onerror 最終觸發 | 超時時間不可控,瀏覽器自行決定 |
| 跨域無 CORS | onerror 觸發,但無錯誤細節 | 無法區分 404/403/跨域錯誤 |
| SVG 向量圖 | 部分舊瀏覽器 width 為 0 直到渲染完成 | 需額外檢查 naturalWidth |
| CSS 背景圖專用 (不插入 DOM) | 此法完美適用 | 無 |
function loadImage(url, timeout = 10000) {
return new Promise((resolve, reject) => {
const img = new Image();
const timer = setTimeout(() => {
cleanup();
reject(new Error('載入超時: ' + url));
}, timeout);
img.onload = () => { cleanup(); resolve(img); };
img.onerror = () => { cleanup(); reject(new Error('載入失敗: ' + url)); };
img.src = url;
function cleanup() {
clearTimeout(timer);
img.onload = img.onerror = null;
}
});
}
// 使用
loadImage('banner.jpg')
.then(img => { document.body.style.backgroundImage = `url(${img.src})`; })
.catch(err => { console.error(err); document.body.style.backgroundColor = '#333'; });
// 預載入多張背景圖,全部就緒再切換類別名觸發 CSS 動畫
Promise.all([
loadImage('bg1.jpg'),
loadImage('bg2.jpg'),
loadImage('bg3.jpg')
]).then(imgs => {
document.body.classList.add('bg-loaded');
// 或依序輪播
}).catch(err => console.error('部分圖片載入失敗', err));
background-image + @supports + JS 事件瀏覽器原生支援 background-image 載入事件嗎?**不支援**。但可用以下 Hack:
// 建立一個隱藏 div,套用背景圖,監測其 computed style 變化 (極不推薦,效能差)
// 或使用 預載入,配合 onload 事件
const link = document.createElement('link');
link.rel = 'preload';
link.as = 'image';
link.href = 'bg.jpg';
link.onload = () => { /* 背景圖已在快取,直接套用 */ };
document.head.appendChild(link);
new Image().width 檢測是判斷背景圖載入最輕量、相容性最好的方法。務必配合 onload/onerror 異步回調、超時機制、Promise 封裝,才能應對真實網路環境。生產環境建議搭配 preload、Service Worker 離線快取、WebP/AVIF 格式優化。