javascript - Gmail 类似预加载器

标签 javascript

我有一个拥有重 Assets 的 SPA:

  • 一个 JavaScript 文件:3Mb
  • 一个样式表文件:近 1Mb
  • 两种字体:700Kb

在正常连接的情况下,文件下载速度很快,不到 3 秒。但你可以想象对于连接速度慢的用户来说,这种体验将是多么令人沮丧,他可能最终会关闭窗口。

一种解决方案是使用经典的预加载器,例如 Pace,但这还不够好。

我的解决方案:

我会在大 script 的不同点调用一些代码文件:

  console.log('progress at 0 %') // at the top
  // code to update the progress bar

  console.log('progress at 23 %') // Somewhere else
  // code to update the progress bar

然后在底部我只听 $(document).ready()删除进度条。

我的问题:

是否有更好的解决方案,或者从所有scripts获取用户下载了多少还剩多少下载的方法stylesheets ...?

最佳答案

如果您要包含一个较小的内联 JavaScript 来引导应用程序的其余部分,则可以使用 XHR 进度事件。

想象一下内联的 javascript:

var appScript = document.createElement('script')
var xhr = new XMLHttpRequest();
xhr.addEventListener('progress', function (e) {
    var percent = e.loaded / e.total
    console.log('loaded', percent)
    // update loader
})
xhr.addEventListener('load', function () {
    appScript.innerHTML = this.responseText
    document.body.appendChild(appScript)
    // ^ at this point the app javascript will run
})
xhr.open('GET', '/js/app.js')
xhr.send()

这应该允许您监控应用程序的加载进度。

关于javascript - Gmail 类似预加载器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36141210/

相关文章:

javascript - 跨域javascript访问localhost。可能的?

javascript - Alfresco 使用 js 将类别应用到文档

javascript - meteor 错误: ENOTEMPTY: directory not empty

javascript - 在 jQuery 过滤器箭头函数中使用它

javascript - js 中意外的 } 标记 - 尝试学习 ajax

javascript - 如何使地址栏在移动浏览器上始终可见?

javascript - Angular 自定义指令无法更改 ng-model 的值

javascript - Ember.js 中组件 Handlebars 内的 "if" Handlebars

javascript - 在 for 循环中从输入区域获取增量值

javascript - 从 td 获取值(value)