欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

基于Javascript實現(xiàn)文件實時加載進度的方法

 更新時間:2016年10月12日 11:06:46   作者:Tiny_z  
不知道大家有沒有發(fā)現(xiàn)在現(xiàn)在的移動頁面上,有很多情況需要加載大量的資源。但是移動端的訪問速度和pc還是有很大的差距,有些時候需要一些取巧的方式來提升用戶體驗,而實時顯示加載進度就是其中一種。這篇文章就給大家分享了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é)議要走http 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、測試的時候,需要把文件放到服務器上,走本地的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)的這個功能還是很實用的,希望能對大家的學習或者工作帶來一定的幫助,如果有疑問大家可以交流。

相關(guān)文章

最新評論