我有一个拥有重 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/