因為我們無法通過任何方法獲取整個頁面的大小和當(dāng)前加載了多少,所以想制作一個加載進(jìn)度條的唯一辦法就是模擬。那要怎么模擬呢?
我們知道,頁面是從上往下執(zhí)行的,也就是說我們可以大致估算出在頁面的某個位置加載了多少,而后用jq模擬出一個進(jìn)度條來顯示。
首先我們先畫一個進(jìn)度條的樣子,也就是上圖圖中的樣子,這個不用過多說明,自己看代碼
CSS
*{margin:0;padding:0;font-size:12px} .loading{position:relative;top:0;left:0} .text input{float:left;color:#fff;height:32px;line-height:34px;padding:0 15px;background:#A70000;border:0} .jindu{float:left;margin-left:14px;color:#fff;width:150px;height:32px;line-height:32px;background:#000;position:relative} .jindu b{color:#A70000;font-size:0px;border-width:10px;border-color:transparent transparent transparent #A70000;border-style:dotted dotted dotted solid;position:absolute;left:-16px;top:5px} .jindu .jindu2{width:0px;height:32px;line-height:32px;background:#A70000;position:absolute} .jindu .text{width:150px;height:32px;line-height:32px;text-align:center;position:absolute}
HTML
<div class="loading"> <div class="text"><input type="button" value="正在初始化"></div> <div class="jindu"> <b></b> <div class="jindu2"></div> <div class="text">頁面總進(jìn)度 <font>0</font>%</div> </div> </div>
這時候注意了,我們要引用jquery庫,引用的位置不是在head區(qū)域,而是緊接著html代碼下面寫。為什么要這樣,因為樣式我們放head里的原因是保證頁面加載第一步就把樣式加載好,這樣頁面不會亂。而JS則不需要,再加上頁面上大的文件主要也就是js,所以放在body里加載js是為了進(jìn)度條考慮。
進(jìn)度條畫好了,jquery引用了,我們現(xiàn)在要寫個方法,也就是可以讓進(jìn)度條動起來
var loading = function(a,b){ var c = b*1.5; if(b==100){ $('.loading .jindu2').animate({width:c+'px'},500,function(){ $('.loading input').val(a); $('.loading font').text(b); $('.loading').animate({top:'-32px'},1000,function(){ alert('頁面加載完畢'); }); }); }else{ $('.loading .jindu2').animate({width:c+'px'},500,function(){ $('.loading input').val(a); $('.loading font').text(b); }); } };
這里我寫了個loading(a,b),兩個參數(shù)分別是顯示加載內(nèi)容提示信息和加載進(jìn)度百分比,然后,我用了其他幾個js庫做加載進(jìn)度測試
<script type="text/javascript">loading('正在加載jQuery UI',30);</script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js"></script> <script type="text/javascript">loading('正在加載Chrome Frame',50);</script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/chrome-frame/1.0.2/CFInstall.min.js"></script> <script type="text/javascript">loading('正在加載EXTJS',70);</script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/ext-core/3.1.0/ext-core.js"></script> <script type="text/javascript">loading('正在加載mootools',90);</script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/mootools/1.4.1/mootools-yui-compressed.js"></script> <script type="text/javascript">loading('正在加載dojo',100);</script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/dojo/1.6.1/dojo/dojo.xd.js"></script>