Track Image Loading效果程式碼分析_javascript技巧
最後更新:2017-01-19
來源:互聯網
上載者:User
目的
在圖片的載入過程中,提供定義圖片載入成功或載入失敗/逾時時的回呼函數,並確保執行。
動機
原生JavaScript已經對 Image 對象提供了 onload 和 onerror 註冊事件。但在瀏覽器緩衝及其他因素的影響下,使用者在使用回退按鈕或者重新整理頁面時 onload 事件常常未能穩定觸發。在我開發的相簿系統中,我希望圖片能根據自訂的大小顯示以免導致頁面變形,例如最寬不得超過500px,而小於500px寬度的圖片則按原大小顯示。CSS2 提供了 max-width 屬效能夠幫組我們實現這一目的。但很遺憾,挨千刀的IE6並不支援。
IE6一個彌補的辦法就是通過註冊 img.onload 事件,待圖片載入完成後自動調整大小。以下代碼取自著名的Discuz!論壇系統4.1版本對顯示圖片的處理。
<img src="yun_qi_img/47104p155.jpg" border="0"
onload="if(this.width>screen.width*0.7) {this.resized=true; this.width=screen.width*0.7;
this.alt='Click here to open new windownCTRL+Mouse wheel to zoom in/out';}"
onmouseover="if(this.width>screen.width*0.7) {this.resized=true; this.width=screen.width*0.7; this.style.cursor='hand'; this.alt='Click here to open new windownCTRL+Mouse wheel to zoom in/out';}"
onclick="if(!this.resized) {return true;} else {window.open('http://img8.imagepile.net/img8/47104p155.jpg');}"
onmousewheel="return imgzoom(this);">
前文已述,瀏覽器並不保證事件處理函數執行。所以需要一個更穩定的方式跟蹤圖片載入過程,並執行設定的回呼函數。
實現
image.complete 屬性標示的是圖片載入狀態,其值如果為ture,則表示載入成功。圖片不存在或載入逾時則值為false。利用 setInterval() 函數定時檢查該狀態則可以實現跟蹤圖片載入的狀況。代碼片斷如下:
ImageLoader = Class.create();
ImageLoader.prototype = {
initialize : function(options) {
this.options = Object.extend({
timeout: 60, //60s
onInit: Prototype.emptyFunction,
onLoad: Prototype.emptyFunction,
onError: Prototype.emptyFunction
}, options || {});
this.images = [];
this.pe = new PeriodicalExecuter(this._load.bind(this), 0.02);
},
........
}
利用Prototype 的PeriodicalExecuter類建立一個定時器,每隔20毫秒檢查一次圖片的載入情況,並根據狀態執行 options 參數中定義的回呼函數。
使用
var loader = new ImageLoader({
timeout: 30,
onInit: function(img) {
img.style.width = '100px';
},
onLoad: function(img) {
img.style.width = '';
if (img.width > 500)
img.style.width = '500px';
},
onError: function(img) {
img.src = 'error.jpg'; //hint image
}
});loader.loadImage(document.getElementsByTagName('img'));
上面的代碼定義圖片最初以100px顯示,載入成功後如果圖片實際寬度超過500px,則再強制定義為500px,否則顯示原大小。如果圖片不存在或載入逾時(30秒為逾時),則顯示錯誤圖片。
同理,可以應用 ImageLoader 的回呼函數來根據需求自訂效果,例如預設顯示loading,載入完成後再顯示原圖;圖片首先灰階顯示,載入完成後再恢複亮度等等。例如:
//need scriptaculous effects.js
var loader = new ImageLoader({
onInit: function(img) {
Element.setOpacity(img, 0.5); //預設5級透明
},
onLoad: function(img) {
Effect.Appear(img); //恢複原圖顯示
}
});
附樣本中包含完整的代碼及使用pconline圖片為例的測試, 注意 範例中使用了最新的Prototype 1.5.0_rc1。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 //EN">
<html>
<head>
<script src="prototype1.5.0_rc1.js"></script>
<script src="validation1.5.3/effects.js"></script>
</head>
<body>
<img id="img0" src="yun_qi_img/fdl.gif" />
<img id="img1" src="yun_qi_img/fdl.gif" />
<img id="img2" src="yun_qi_img/fdl.gif" />
<br />載入失敗測試<br />
<img id="img2" src="yun_qi_img/fdl.gif" />
<script type="text/javascript">
ImageLoader = Class.create();
ImageLoader.prototype = {
initialize : function(options) {
this.options = Object.extend({
timeout: 60, //60s
onInit: Prototype.emptyFunction,
onLoad: Prototype.emptyFunction,
onError: Prototype.emptyFunction
}, options || {});
this.images = [];
this.pe = new PeriodicalExecuter(this._load.bind(this), 0.02);
},
loadImage : function() {
var self = this;
$A(arguments).each(function(img) {
if (typeof(img) == 'object')
$A(img).each(self._addImage.bind(self));
else
self._addImage(img);
});
},
_addImage : function(img) {
img = $(img);
img.onerror = this._onerror.bind(this, img);
this.options.onInit.call(this, img);
if (this.options.timeout > 0) {
setTimeout(this._ontimeout.bind(this, img), this.options.timeout*1000);
}
this.images.push(img);
if (!this.pe.timer)
this.pe.registerCallback();
},
_load: function() {
this.images = this.images.select(this._onload.bind(this));
if (this.images.length == 0) {
this.pe.stop();
}
},
_checkComplete : function(img) {
if (img._error) {
return true;
} else {
return img.complete;
}
},
_onload : function(img) {
if (this._checkComplete(img)) {
this.options.onLoad.call(this, img);
img.onerror = null;
if (img._error)
try {delete img._error}catch(e){}
return false;
}
return true;
},
_onerror : function(img) {
img._error = true;
img.onerror = null;
this.options.onError.call(this, img);
},
_ontimeout : function(img) {
if (!this._checkComplete(img)) {
this._onerror(img);
}
}
}
var loader = new ImageLoader({
timeout: 30,
onInit: function(img) {
img.style.width = '100px';
},
onLoad: function(img) {
img.style.width = '';
if (img.width > 500) {
img.style.width = '500px';
}
},
onError: function(img) {
img.src = 'yun_qi_img/fdl.gif';
}
});
loader.loadImage(document.getElementsByTagName('img'));
/*
var loader = new ImageLoader({
timeout: 30,
onInit: function(img) {
Element.setOpacity(img, 0.5);
},
onLoad: function(img) {
Effect.Appear(img);
},
onError: function(img) {
img.src = 'yun_qi_img/fdl.gif';
}
});
*/
/*
$A(document.getElementsByTagName('img')).each(
function(img) {
img.onload = function() {
img.style.width = '300px';
}
}
);
*/
</script>
</body>
</html>