我有一个包含大量大图片的网站,我想在加载所有内容时显示一个Twitter引导进度条。
有可能这样做吗? jquery是否有办法跟踪页面加载的进度?
我想显示一个进度条,直到所有的css,js和图像等都被下载。
答案 0 :(得分:1)
您可以尝试这样的事情:
HTML
<div class="progress progress-striped active">
<div class="bar"></div>
</div>
<div class="imagelist">
<img src="http://studio7designs.com/wp-content/uploads/green-grass.jpeg"/>
<img src="http://studio7designs.com/wp-content/uploads/rowboat-600x398.jpg"/>
<img src="http://studio7designs.com/wp-content/uploads/blue-wheat-grass.jpeg"/>
<img src="http://studio7designs.com/wp-content/uploads/rocks.jpg"/>
<img src="http://studio7designs.com/wp-content/uploads/sun-grass-golden.jpg"/>
<img src="http://studio7designs.com/wp-content/uploads/blue-water-photo.jpg"/>
<img src="http://studio7designs.com/wp-content/uploads/flight.jpg"/>
</div>
的Javascript
$.fn.imagesLoaded = function (callback, onEach) {
var elems = this.filter('img'),
len = elems.length,
blank = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
elems.bind('load.imgloaded', function () {
if(typeof onEach === 'function'){
onEach(len, elems.length); // runs on every image load
}
if (--len <= 0 && this.src !== blank) {
elems.unbind('load.imgloaded');
callback.call(elems, this);
}
}).each(function () {
// cached images don't fire load sometimes, so we reset src.
if (this.complete || this.complete === undefined) {
var src = this.src;
// webkit hack from http://groups.google.com/group/jquery-dev/browse_thread/thread/eee6ab7b2da50e1f
// data uri bypasses webkit log warning (thx doug jones)
this.src = blank;
this.src = src;
}
});
return this;
};
$(document).ready(function () {
var progress = $('.progress');
var progressbar = progress.children('.bar');
$('.imagelist img').imagesLoaded(function () {
progressbar.width('100%');
progress.fadeOut();
}, function (left, total) {
progressbar.width((total - left) / total * 100 + '%');
});
});
我使用了Paul Irish编写的.imagesLoaded()代码,并添加了每次加载图像时触发的附加回调。因此,对于每个加载的图像,进度条都会进行。
它并不完全准确,因为它不会跟踪加载任何特定文件的数量,并且我不完全确定可以在不使此代码复杂化的情况下进行,因此进度条仅在加载图像时而不是在加载时更改它正在加载。
我希望这会有所帮助。