如何获得下载< script>的进度? [英] How can I get the progress of a downloading <script>?

查看:69
本文介绍了如何获得下载< script>的进度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我正在创造一款游戏。我有一个小脚本,其任务是加载所有资产,并在资产加载时向用户显示进度条。

一个这样的资产是一个相当大的脚本,它包含游戏逻辑。也许超过3 MB。



如何向用户显示第二个脚本的加载进度?

解决方案

< script> 标签仅触发加载错误事件;他们不会触发进度事件。但是,在现代浏览器中, Ajax请求执行支持进度事件。您可以通过Ajax加载脚本内容并监视进度,然后在加载完成时将脚本内容放入新的< script> 元素中:

  var req = new XMLHttpRequest(); 

//报告进度事件
req.addEventListener(progress,function(event){
if(event.lengthComputable){
var percentComplete = event。 loaded / event.total;
// ...
} else {
//由于总大小未知,无法计算进度信息
}
},假);

//将responseText加载到新的脚本元素
req.addEventListener(load,function(event){
var e = event.target;
var s = document.createElement(script);
s.innerHTML = e.responseText;
// or:s [s.innerText!= undefined?innerText:textContent] = e .responseText
document.documentElement.appendChild(s);

s.addEventListener(load,function(){
//在新脚本执行后运行...
});
},false);

req.open(GET,foo.js);
req.send();

对于不支持Ajax的旧浏览器 progress ,您可以构建进度报告界面,以便在第一个 progress 事件之后显示加载栏(否则,如果不存在进度有火的事件)。


Let's say, for example, I'm creating a game. I have a small script whose job is to load all the assets and present a progress bar to the user while the assets load.

One such asset is a rather large script which contains the game logic. Perhaps upwards of 3 MB.

How can I show the loading progress of the second script to the user?

解决方案

<script> tags only fire load and error events; they do not fire progress events. However, in modern browsers, Ajax requests do support progress events. You can load your script content and monitor progress through Ajax, and then place the script contents into a new <script> element when the load completes:

var req = new XMLHttpRequest();

// report progress events
req.addEventListener("progress", function(event) {
    if (event.lengthComputable) {
        var percentComplete = event.loaded / event.total;
        // ...
    } else {
        // Unable to compute progress information since the total size is unknown
    }
}, false);

// load responseText into a new script element
req.addEventListener("load", function(event) {
    var e = event.target;
    var s = document.createElement("script");
    s.innerHTML = e.responseText;
    // or: s[s.innerText!=undefined?"innerText":"textContent"] = e.responseText
    document.documentElement.appendChild(s);

    s.addEventListener("load", function() {
        // this runs after the new script has been executed...
    });
}, false);

req.open("GET", "foo.js");
req.send();

For older browsers that don't support Ajax progress, you can build your progress-reporting UI to show a loading bar only after the first progress event (or otherwise, show a generic spinner if no progress events ever fire).

这篇关于如何获得下载&lt; script&gt;的进度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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