new Image() 設定 src 後,瀏覽器非同步載入圖片。在 onload 觸發前,width/height 均為 0。如何最快拿到尺寸?
var img = new Image();
img.src = 'photo.jpg?' + Date.now(); // 防快取
console.log(img.width, img.height); // 0, 0 —— 圖片尚未載入
onload 回呼(標準、最可靠)var img = new Image();
img.onload = function() {
console.log('onload:', img.width, img.height);
};
img.src = 'photo.jpg?' + Date.now();
缺點:大圖載入慢,需等完全下載完才觸發。
complete + onload 混合(利用瀏覽器快取)var img = new Image();
img.src = 'photo.jpg'; // 無時間戳,允許快取
if (img.complete) {
console.log('from cache:', img.width, img.height);
} else {
img.onload = function() {
console.log('onload:', img.width, img.height);
};
}
原理:若圖片已在快取,complete === true 且尺寸即時可用,無需等待。
var img = new Image();
img.src = 'photo.jpg?' + Date.now();
var start = Date.now();
var timer = setInterval(function() {
if (img.width > 0 || img.height > 0) {
console.log('polling:', img.width, img.height, '耗時', Date.now() - start, 'ms');
clearInterval(timer);
}
}, 40); // 40ms 檢測一次
img.onload = function() {
console.log('onload final:', img.width, img.height, '耗時', Date.now() - start, 'ms');
clearInterval(timer);
};
| 瀏覽器 | 輪詢首次拿到尺寸 | onload 觸發 | 說明 |
|---|---|---|---|
| Chrome | ~40ms (第1次輪詢) | ~200ms | 極快,首包即回傳尺寸 |
| Firefox | ~80-120ms | ~300ms | 需數次輪詢 |
| IE 7-10 | ~120-200ms | ~400ms | 較慢 |
function getImageSize(url, callback) {
var img = new Image();
var timer, start = Date.now();
function done(w, h, source) {
clearInterval(timer);
img.onload = img.onerror = null;
callback(w, h, source, Date.now() - start);
}
img.onload = function() { done(img.width, img.height, 'onload'); };
img.onerror = function() { done(0, 0, 'error'); };
// 快取命中
if (img.complete) { done(img.width, img.height, 'cache'); return; }
// 輪詢檢測
timer = setInterval(function() {
if (img.width > 0 || img.height > 0) {
done(img.width, img.height, 'polling');
}
}, 30);
img.src = url;
}
// 使用
getImageSize('photo.jpg', function(w, h, source, time) {
console.log('尺寸:', w, 'x', h, '來源:', source, '耗時:', time + 'ms');
});
HTMLImageElement.decode():非同步解碼,回傳 Promise,解碼完成即有尺寸。createImageBitmap():OffscreenCanvas 環境下高效解碼。data-width 屬性),完全避免客戶端檢測。