在排版中,圖片永遠是最不可控的元素。傳統做法多半是等 onload 觸發後,取得圖片的實際寬高再進行縮放運算——問題是,在圖片載入完成之前,它已經以原始尺寸把版面撐破了一次。使用者看到的往往是一段「先爆版、再回正」的跳動過程。
QQ 空間的日誌頁對這一點做了改良:先讓容器保持穩定,等 onload 完成後才把原圖顯示出來,視覺上就平順得多。
與其等圖片載完,不如提早知道它的尺寸。imgReady 這個函式能在 DOM ready 階段就跨瀏覽器取得圖片的原始寬高,不必等 img 真的下載完畢。autoIMG 正是建立在它之上:支援 max-width 的瀏覽器直接走 CSS 方案,不支援的則用「預載入 + 尺寸就緒偵測」的方式補足。
// jQuery.autoIMG.js v0.2
// Tang Bin - https://planeArt.cn/ - MIT Licensed
(function ($) {
var
// 設置加載狀態的替換圖像
tempPath = './images/loading.png',
// 設置加載錯誤的替換圖像
errorPath = './images/error.png',
// 檢測是否支持 css2.1 max-width 屬性
isMaxWidth = 'maxWidth' in document.documentElement.style,
// 檢測是否 IE7 浏覽器
isIE7 = !-[1,] && !('prototype' in Image) && isMaxWidth;
new Image().src = tempPath;
$.fn.autoIMG = function () {
var $this = this,
maxWidth = $this.width(); // 獲取容器寬度
return $this.find('img').each(function (i, img) {
// 支持 max-width 者直接套用,否則走下面的預加載方式
if (isMaxWidth) return img.style.maxWidth = maxWidth + 'px';
var path = img.getAttribute('data-src') || img.src,
next = img.nextSibling,
parent = img.parentNode,
temp = new Image();
// 先隱藏原圖並換成 loading 圖
img.style.display = 'none';
img.removeAttribute('src');
img.parentNode.removeChild(img);
temp.src = tempPath;
next ? next.insertBefore(temp) : parent.appendChild(temp);
// 圖片尺寸就緒後的處理
imgReady(path, function (width, height) {
if (width > maxWidth) {
height = maxWidth / width * height; // 等比例縮放
width = maxWidth;
temp.parentNode.removeChild(temp); // 移除 loading 圖
img.style.display = '';
img.style.width = width + 'px';
img.style.height = height + 'px';
img.setAttribute('src', path);
next ? next.insertBefore(img) : parent.appendChild(img);
}
}, function () {
// 載入失敗
temp.src = errorPath;
temp.title = 'Image load error!';
});
});
};
// IE7 縮放圖片會失真,以私有屬性搭配三次插值改善
isIE7 && (function (c, d, s) {
s = d.createElement('style');
d.getElementsByTagName('head')[0].appendChild(s);
s.styleSheet ? (s.styleSheet.cssText += c) : s.appendChild(d.createTextNode(c));
})('img {-ms-interpolation-mode:bicubic}', document);
// 取得圖片檔頭的尺寸資料
// @param {String} 圖片路徑
// @param {Function} 尺寸就緒回呼 (width, height)
// @param {Function} 載入錯誤回呼(可選)
var imgReady = function (url, callback, error) {
var width, height, offsetWidth, offsetHeight, intervalId, check, div,
accuracy = 1024,
doc = document,
container = doc.body || doc.getElementsByTagName('head')[0],
img = new Image();
img.src = url;
// 命中快取則直接回傳
if (img.complete) {
return callback(img.width, img.height);
}
// 插入隱藏元素,監聽尺寸就緒狀態
if (container) {
div = doc.createElement('div');
div.style.cssText = 'visibility:hidden;position:absolute;left:0;top:0;width:1px;height:1px;overflow:hidden';
div.appendChild(img);
container.appendChild(div);
width = img.offsetWidth;
height = img.offsetHeight;
check = function () {
offsetWidth = img.offsetWidth;
offsetHeight = img.offsetHeight;
// 尺寸一旦改變,代表瀏覽器已讀到檔頭並完成佔位
if (offsetWidth !== width || offsetHeight !== height ||
offsetWidth * offsetHeight > accuracy) {
clearInterval(intervalId);
callback(offsetWidth, offsetHeight);
img.onload = null;
div.innerHTML = '';
div.parentNode.removeChild(div); // 避免 IE 記憶體洩漏
}
};
check();
intervalId = setInterval(check, 150);
}
// 保險:等圖片完全載入
img.onload = function () {
callback(img.width, img.height);
img.onload = img.onerror = null;
clearInterval(intervalId);
container && img.parentNode.removeChild(img);
};
// 載入錯誤
img.onerror = function () {
error && error();
clearInterval(intervalId);
container && img.parentNode.removeChild(img);
};
};
})(jQuery);
autoIMG 壓縮後僅約 1.74 KB,實測可正常運作於 Chrome、Firefox、Safari、Opera 以及 IE6、IE7、IE8 等瀏覽器。
呼叫方式相當直覺:
$('#demo p').autoIMG();
線上範例:https://demo.jb51.net/js/2011/autoimg/
原本以為有了 imgReady 打底,寫出這個縮放外掛應該輕鬆愉快,沒想到在 WebKit 核心的瀏覽器上栽了跟頭,折騰了好一陣子,最後只好回頭修改 imgReady 的實作才解決。瀏覽器核心的細微差異,往往才是前端開發最耗時間的部分。