gpt4 book ai didi

javascript - 下载小文件时如何在 JavaScript 中显示进度条?

转载 作者:行者123 更新时间:2023-11-29 02:40:21 25 4
gpt4 key购买 nike

我编写了以下函数来处理 AJAX 请求以获取数据:

var xhr = createCORSRequest('GET', url);
if (!xhr) {
alert('CORS not supported');
return;
}
xhr.onload = function() {
var txt1 = xhr.responsetxt1;
var heading = getheading(txt1);

if (heading == 'PASS') {
var file = "My_URL" + ".js";
downloadFile(file);
//My code to display a progress bar here?
} else {
//Logic to handle failure to load
}
};

这是我的 downloadFile 函数,用于下载文件。但是,我不明白如何:

  • 检查下载是否完成。
  • 显示进度条以显示进度。

如果您可以添加有关其工作原理的说明,那就太好了。谢谢。

function downloadFile(fileName) {
(function(d) {
var ref = d.getElementsByTagName('script')[0];
var js = d.createElement('script');
js.src = fileName;
ref.parentNode.insertBefore(js, ref);
// My code to display a progress bar here?
}(document));
}

最佳答案

AFAIK,脚本元素没有进度事件。最好的办法是使用 XHR 获取脚本的主体,然后依靠浏览器缓存进行第二次提取。问题是您的脚本随后需要由浏览器解析,而且似乎没有相应的事件。

我的解决方案是纯 JS,因此您可以根据您使用的任何框架对其进行调整。它假定实际下载将占总时间的 70% 左右,并将 20% 分配给浏览器解析。我使用了一个非缩小版本的真棒 three.js 3D库作为一个大的源文件。

因为它在另一个沙盒中,所以进度调用不准确,但如果您提供自己的脚本,这应该不是问题。

请记住,这是一个相当精简的实现。例如,我使用一个简单的 HR 作为进度条。

//this is a rough size estimate for my example file
let TOTAL_ESTIMATE = 1016 * 1024;
// I use a hr as a
let bar = document.getElementById("progressbar");
let button = document.getElementById("dlbtn");

var js; // to hold the created dom element
var fileName; // to hold my cacheBusted script adress

/* this function will be called several times during (the first) download, with info about how much data is loaded */

function onProgress(e) {
var percentComplete = e.loaded / TOTAL_ESTIMATE;
if (e.lengthComputable) {
percentComplete = e.loaded / e.total;
}
p = Math.round(percentComplete * 100);
console.log("progress", p + "%,", e.loaded, "bytes loaded")
bar.style = "width: " + (5 + .6 * p) + "%"; // I just assume dl will be around 60-70% of total time

}

/* this function is called when info comes. at the end of the initial download, the readystate will be 4 so we then set the file's src attribute, triggering a re-download but taking advantage of the browser's cache. It's not ideal, and simply `eval` ing the data would probably yield better results. I just assumed you wanted a <script> tag on your page, and for it to be evaluated. */
function onReadyState(e) {
let r = e.target;
//this is lifted almost verbatim from http://vanilla-js.com/ ;)
if (r.readyState != 4 || r.status != 200)
return;
let l = r.responseText.length;
console.log("Success !", l, "bytes total (" + Math.round(l / 1024) + " KB )");
bar.style = "width: 70%";
//just add / to next line to toggle ending methods
/* you could speed up the proces by simply eval()ing the returned js. like so (please be aware of security concerns) :
eval.bind(window)(r.responseText);
onScriptLoaded();
/*/

js.src = fileName;
bar.style = "width: 80%";
var ref = document.getElementsByTagName('script')[0];
ref.parentNode.insertBefore(js, ref);
//*/

};

//this is called when the script has been evaluated :
function onScriptLoaded() {
bar.style = "width: 100%; background-color: lightgreen;";
button.disabled = false;
console.log("script has been evaluated ?", THREE ? "yes" : "no"); // the demo file exposes window.THREE
}

function downloadFile(file) {
button.disabled = true;
(function(d) {
// this helps to test this script multiple times. don't keep it
fileName = file + "?bustCache=" + new Date().getTime();


console.log("inserting new script");
js = d.createElement('script');
js.type = "text/javascript";
js.defer = "defer";
js.async = "async";
var r = new XMLHttpRequest();
bar.style = "width: 5%"; //always react ASAP
r.addEventListener("progress", onProgress);
r.open("GET", fileName, true);
r.onreadystatechange = onReadyState;
js.onload = onScriptLoaded;
r.send();
// My code to display a progress bar here?
}(document));
}
#progressbar {
height: 6px;
border-radius: 3px;
width: 0%;
border-color: green;
background-color: green;
}
<button onclick="downloadFile('https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.js', this)" id="dlbtn">Download</button>
<script id="dummy" type="text/javascript">
console.log("dummy script ready")
</script>
<hr id="progressbar" align="left" />

关于javascript - 下载小文件时如何在 JavaScript 中显示进度条?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44656595/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com