基于Javascript實現(xiàn)文件實時加載進度的方法
我們首先來看看要實現(xiàn)的效果圖

代碼如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
*{margin: 0;padding: 0;}
div{width:200px;height: 30px;border:1px solid #ccc;margin: 50px auto;}
span{display:inline-block;height: 30px;background: #abcdef;}
</style>
</head>
<body>
<div>
<span id="loading"></span>
</div>
<!-- 圖片需要自己添加到本地 協(xié)議要走h(yuǎn)ttp or https -->
<script>
var img_arr = ['1.jpg','2.jpg','3.png'];
var nums = img_arr.length;
var start = 0;
for(var i in img_arr){
var img = document.createElement('img');
img.src = img_arr[i];
(function(j){
img.onload = function(){
start++;
if(start == nums){
console.log('全部加載完成');
}
document.getElementById('loading').style.width = (start/nums)*100 + '%';
};
img.onerror = function(){
start++;
console.log(img_arr[j] + '失敗');
document.getElementById('loading').style.width = (start/nums)*100 + '%';
}
})(i);
}
</script>
</body>
</html>
有些情況下,資源會加載失敗,但是頁面又需要顯示出來。這里我是把失敗的情況就跳過了,如果有需要,可以考慮重新?lián)Q資源加載
注意事項
1、測試的時候,需要把文件放到服務(wù)器上,走本地的file協(xié)議是看不到效果的
2、測試的時候,可以把網(wǎng)絡(luò)設(shè)置為2g或者3g,可以方便看到加載的進度,然后禁止使用緩存

拓展
這里只監(jiān)聽了img格式,如果有需要,可以把js和css都加進來
注意:監(jiān)聽js或者css,需要把創(chuàng)建的資源追加到頁面中,要不然監(jiān)聽不到onload和onerror事件
<script>
var script_arr = ['http://cdn.bootcss.com/jquery/3.1.0/jquery.slim.js','http://cdn.bootcss.com/jquery/3.0.0-rc1/jquery.js','http://cdn.bootcss.com/jquery/3.0.0-beta1/jquery.slim.min.js'];
var nums = script_arr.length;
var start = 0;
for(var i in script_arr){
var script = document.createElement('script');
script.src = script_arr[i];
(function(j){
document.body.appendChild(script);
script.onload = function(){
start++;
if(start == nums){
console.log('全部加載完成');
}
document.getElementById('loading').style.width = (start/nums)*100 + '%';
};
script.onerror = function(){
start++;
console.log(srcript_arr[j] + '失敗');
document.getElementById('loading').style.width = (start/nums)*100 + '%';
}
})(i);
}
</script>

總結(jié)
以上就是這篇文章的全部內(nèi)容了,本文實現(xiàn)的這個功能還是很實用的,希望能對大家的學(xué)習(xí)或者工作帶來一定的幫助,如果有疑問大家可以交流。
相關(guān)文章
完美兼容各大瀏覽器獲取HTTP_REFERER方法總結(jié)
發(fā)現(xiàn)一個關(guān)于瀏覽器兼容的問題,當(dāng)用JS 執(zhí)行代碼 window.location.href=”http://www.dbjr.com.cn” 來進行跳轉(zhuǎn)的時候,F(xiàn)irefox 可以獲取到到HTTP_REFERER頁面,但是在IE中這一項為空2014-06-06
JavaScript將數(shù)組轉(zhuǎn)換成CSV格式的方法
這篇文章主要介紹了JavaScript將數(shù)組轉(zhuǎn)換成CSV格式的方法,實例分析了javascript使用valueOf方法將數(shù)組值轉(zhuǎn)換為csv格式字符串的技巧,非常具有實用價值,需要的朋友可以參考下2015-03-03
JavaScript實現(xiàn)提交模式窗口后刷新父窗口數(shù)據(jù)的方法
這篇文章主要介紹了JavaScript實現(xiàn)提交模式窗口后刷新父窗口數(shù)據(jù)的方法,涉及javascript窗口交互的相關(guān)操作技巧,需要的朋友可以參考下2017-06-06
webpack本地開發(fā)環(huán)境無法用IP訪問的解決方法
下面小編就為大家分享一篇webpack本地開發(fā)環(huán)境無法用IP訪問的解決方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-03-03

