如何在通过 webpack 加载单个捆绑的 javascript 文件时显示进度条? [英] How to display a progress bar while loading single bundled javascript file by webpack?

查看:21
本文介绍了如何在通过 webpack 加载单个捆绑的 javascript 文件时显示进度条?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题是关于 webpack 的.将几乎所有内容打包成一个加载在 index.html 中的 bundle.js 后,bundle.js 文件大约为 2M,需要几秒钟才能加载.

The question is concerning webpack. After packing almost everything into a single bundle.js which is loaded in index.html, the bundle.js file is about 2M and requires several seconds to load.

我想在隐藏所有内容的同时显示一个指示加载进度的进度条.仅启用用户交互并在加载完成后显示内容,这正是 Gmail 使用的内容.

I'd like to display a progress bar indicating loading progress while hiding all the content. Only enable user interaction and show the content after loading is done, exactly the one that Gmail is using.

是否可以使用 webpack 来做到这一点?如何?

Is it possible to use webpack to do that? How?

谢谢!

推荐答案

自从下载JS 的源代码并将其附加DOM 可能会很痛苦,您通常会使用 jQuery.getScript(url [, success ]).但是您不能在该调用上设置进度函数.

Since downloading the source of a JS and appending it to the DOM could be quite painful, you normally would use jQuery.getScript(url [, success ]). But you can't set a progress function on that call.

我们很幸运:https://api.jquery.com/jquery.getscript/

这是一个简写的Ajax函数,相当于:

This is a shorthand Ajax function, which is equivalent to:

$.ajax({
  url: url,
  dataType: "script",
  success: success
});

jQuery.ajax() 调用中,我们可以设置一个进度函数.

And on an jQuery.ajax() call we can set a progress function.

如果服务器在 http 标头中包含响应大小,我们可以计算进度百分比.否则,我们只能使用每次进度事件调用时接收到的总字节数.

We can calculate the progress percentage if the server includes the response size in http headers. Otherwise we can only use the total received bytes at each progress event call.

$.ajax({
  url: 'https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js', // unminified angular is 1.2mb, perfect for demonstration :)
  dateType: 'script',
  xhr: function()
  {
    var xhr = new window.XMLHttpRequest();
    //Download progress
    xhr.addEventListener("progress", function(evt){
      // do something with progress info
      if (evt.lengthComputable) {
        // we can calculate the percentage
        var percentComplete = evt.loaded / evt.total;
        //Do something with download progress
        console.log(percentComplete);
      } else if (evt.loaded)
        // we only know the received amount and not the total amount
      	console.log('downloaded:',evt.loaded);
    }, false);
    return xhr;
  }
}).done(function( data, textStatus, jqXHR ) {
  console.log('finished');
}).fail(function( jqXHR, settings, exception ) {
  console.log('could not load');
});

<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>

这篇关于如何在通过 webpack 加载单个捆绑的 javascript 文件时显示进度条?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆