[英]Checking that the background image has loaded
這是我的代碼:
$('<div>')
.css('background-image', 'url(' + images[imageToLoad].url + ') no-repeat center center')
.appendTo('#image-container')
.hide()
.load(function () {
loadedImages.push($(this));
});
不知何故, load
背景圖像時, load
事件永遠不會觸發。 我應該捕獲什么事件以了解背景何時加載?
@variant所說的+代碼,因為img onload事件並不總是觸發:
var img = new Image(),
div = $( "<div>" ).appendTo( "#image-container").hide();
img.onload = function(){
if( this.isLoaded ) {
return;
}
this.isLoaded = true;
loadedImages.push(
div.css( "background-image", "url('"+this.src+"') no-repeat center center" )
);
}
img.src = images[imageToLoad].url;
if( ( img.complete || img.readyState === 4 ) && !img.isLoaded ) {
img.onload();
}
這里沒有捕獲事件。
您可以做的是使用IMG
標記預加載圖像並在其上偵聽load
事件。 當它被觸發時,將帶有background-image的div附加到DOM。 圖像已經在瀏覽器的緩存中,加載將是即時的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.