Dan*_*ugg 5 jquery image-processing preloader
我正在开发一个背景图像密集的网站.由于一些图像很大,页面的美学吸引力将不可避免地受到初始加载,可能持续几秒钟.
所以我试图用jQuery创建一个背景图像预加载器,这里是我所在的位置:
$(document).ready(function(e){
$('*')
.each(function(){
if($(this).css('background-image') != 'none'){
//so, i can get the path, where do i go from here?
alert($(this).css('background-image').slice(5, -2));
}
});
});
Run Code Online (Sandbox Code Playgroud)
我使用了一个Image()对象数组,使用从迭代器中提取的路径来加载图像,但是我迷失了从这里开始的地方.
如何确定阵列中的所有图像何时"已加载",以便我可以调用一个函数来淡出预加载窗帘或其他东西?
你应该能够完成这样的事情(未经测试!):
$(document).ready(function(e){
// get a collection of all elements with a BG image
var bgImages = $('*').filter(function(){
return $(this).css('background-image') != 'none');
// get a collection of new images, assigning the sources from the original collection
}).map(function() {
return $("<img />").attr("src", $(this).css('background-image').slice(5, -2));
});
var len = bgImages.length;
var loadCounter = 0;
// use an onload counter to keep track of which ones have loaded
bgImages.load(function() {
loadCounter++;
if(loadCounter == len) {
// we have all loaded
// fade out curtain
}
}).each(function() {
// if we have been pulled up from cache, manually trigger onload
if (this.complete) $(this).trigger("load");
});
});
Run Code Online (Sandbox Code Playgroud)