javascript 如何获取下载 <script> 的进度?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18126406/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I get the progress of a downloading <script>?
提问by andrewrk
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.
其中一项资产是包含游戏逻辑的相当大的脚本。也许超过 3 MB。
How can I show the loading progress of the second script to the user?
如何向用户显示第二个脚本的加载进度?
回答by apsillers
<script>
tags only fire load
and error
events; they do not fire progress
events. However, in modern browsers, Ajax requests dosupport 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:
<script>
只标记火灾load
和error
事件;它们不会触发progress
事件。然而,在现代浏览器中,Ajax 请求确实支持progress
事件。您可以通过 Ajax 加载脚本内容并监控进度,然后<script>
在加载完成后将脚本内容放入一个新元素中:
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).
对于不支持 Ajax 的旧浏览器progress
,您可以构建进度报告 UI 以仅在第一个progress
事件之后显示加载栏(否则,如果没有progress
事件触发,则显示通用微调器)。
回答by Salketer
You might like to have a look at How to show loading status in percentage for ajax response?
您可能想看看如何以百分比显示 ajax 响应的加载状态?
It is to see the status of an AJAX download. Since you are loading a script, it might not be the best way to get the file but it could work. You would then need to put the content received by the ajax call somewhere to execute, and eval is not recommended.
它是查看 AJAX 下载的状态。由于您正在加载脚本,因此它可能不是获取文件的最佳方式,但它可以工作。然后,您需要将 ajax 调用接收到的内容放在某处执行,并且不建议使用 eval。