如果需要在頁面初始加載時顯示加載進度。主要是指圖片很多的情況下:
可以使用第三方Jquery插件
jquery.imgpreload.min.js
調用里面的方法:imgpreload即可,實例如下:
var imgNum = 0;
var images = [];
$(function(){ preloadImg(); });
//里面有兩種方式
function preLoadImg() {
//第一種方式:通過dom方法獲取頁面中的所有img,包括<img>標簽和css中的background-image
/*get all imgs those tag is <img>
var imgs = document.images;
for (var i = 0; i < imgs.length; i++) {
images.push(imgs[i].src);
}
//get all images in style
var cssImages = getallBgimages();
for (var j = 0; j < cssImages.length; j++) {
images.push(cssImages[j]);
}*/
//第二種方式:把所有該網頁上用到的圖片文件都預先放入一個數組里
$.imgpreload(['images/bg1.jpg', 'images/bg2.jpg'], function () {
//此處是顯示進度百分比時需要用到的背景圖,這個可以先加載進去
});
//then push all other images in array to load
images.push("images/test_1.png");
images.push("images/test_2.png");
images.push("images/test_3.png");
//。。。
images.push("images/test_n.png");
/*這里是真正的圖片預加載 preload*/
$.imgpreload(images,
{
each: function () {
/*this will be called after each image loaded*/
var status = $(this).data('loaded') ? 'success' : 'error';
if (status == "success") {
var v = (parseFloat(++imgNum) / images.length).toFixed(2);
$("#percentShow").html(Math.round(v * 100) + "<sup>%</sup>");
}
},
all: function () {
/*this will be called after all images loaded*/
$("#percentShow ").html("100<sup>%</sup>");
$("percentShow").fadeOut(1000);
$(".main").show();
}
});
}
//get all images in style(此方法引用其他博客的)
function getallBgimages() {
var url, B = [], A = document.getElementsByTagName('*');
A = B.slice.call(A, 0, A.length);
while (A.length) {
url = document.deepCss(A.shift(), 'background-image');
if (url) url = /url\(['"]?([^")]+)/.exec(url) || [];
url = url[1];
if (url && B.indexOf(url) == -1) B[B.length] = url;
}
return B;
}
document.deepCss = function (who, css) {
if (!who || !who.style) return '';
var sty = css.replace(/\-([a-z])/g, function (a, b) {
return b.toUpperCase();
});
if (who.currentStyle) {
return who.style[sty] || who.currentStyle[sty] || '';
}
var dv = document.defaultView || window;
return who.style[sty] ||
dv.getComputedStyle(who, "").getPropertyValue(css) || '';
}
Array.prototype.indexOf = Array.prototype.indexOf ||
function (what, index) {
index = index || 0;
var L = this.length;
while (index < L) {
if (this[index] === what) return index;
++index;
}
return -1;
}
這樣就能在頁面圖片很多,且網速很慢的情況下給予用戶一個百分比提示。
在做這個之前,由於每次本地測試加載都很快,百分比瞬間到100%然后消失,為了看上去有那么一回事,我還寫了一個偽百分比進度條,僅供玩耍:
var t = window.setTimeout("preLoad()", 100);
function preLoad() {
$("#loading div").animate({ width: step + "px" }, 50).text(step + "%");
step += 1;
if (step <= 100) {
t = window.setTimeout("preLoad()", 100);
} else {
clearTimeout(t);
$("#loading").fadeOut(1000);
$("#preloadImg").fadeOut(1000);
$(".main").show();
}
(這是一個頁面初始化完成之后,在頁面上有一個模擬百分比不斷增長的過程,到100%后消失進度條,顯示主頁面,不過跟實際頁面加載沒任何關系,可以忽悠不懂且有想要此功能的人,哈哈)