javascript Javascript源文件下载进度?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11265917/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 12:36:02  来源:igfitidea点击:

Javascript source file download progress?

javascriptjquery

提问by Jonathan

I am sourcing a large mapping/widget javascript file (1.3 MB) and wanted to display a progress bar as it loads. I know firebug's net watch tab knows a lot of this information, but I would like something more lightweight. I came across this website: http://blog.greweb.fr/2012/04/work-in-progress/

我正在采购一个大型映射/小部件 javascript 文件 (1.3 MB),并希望在加载时显示进度条。我知道 firebug 的 net watch 选项卡知道很多这些信息,但我想要更轻量的东西。我遇到了这个网站:http: //blog.greweb.fr/2012/04/work-in-progress/

which almost gets me there except that I need to source the file I'm downloading. I didn't see any listeners on jQuery's getScript as the file downloads. Does anyone know how to get at the progress of a sourced file download?

这几乎让我到达那里,除了我需要获取我正在下载的文件。在文件下载时,我没有在 jQuery 的 getScript 上看到任何侦听器。有谁知道如何获取源文件下载的进度?

Thanks in advance!

提前致谢!

回答by sachleen

If you use getScript()you can execute a function using the success callback but that is only when the script has finished loading.

如果您使用,getScript()您可以使用成功回调执行函数,但这仅在脚本完成加载时执行。

I would recommend having a loading indicator image (you can find many at http://ajaxload.info/) and hiding it when the script has loaded.

我建议使用加载指示器图像(您可以在http://ajaxload.info/ 上找到很多)并在脚本加载后隐藏它。

This SOhas a couple of other ideas. One solution is below:

这个 SO有一些其他的想法。一种解决方案如下:

var myTrigger;
var progressElem = $('#progressCounter');
$.ajax ({
    type            : 'GET',
    dataType        : 'xml',
    url             : 'somexmlscript.php' ,
    beforeSend      : function (thisXHR)
    {
        myTrigger = setInterval (function ()
        {
            if (thisXHR.readyState > 2)
            {
                var totalBytes  = thisXHR.getResponseHeader('Content-length');
                var dlBytes     = thisXHR.responseText.length;
                (totalBytes > 0)? progressElem.html (Math.round ((dlBytes/ totalBytes) * 100) + "%") : progressElem.html (Math.round (dlBytes /1024) + "K");
            }
        }, 200);
    },
    complete        : function ()
    {
        clearInterval (myTrigger);
    },
    success         : function (response)
    {
        // Process XML
    }
});

This sets an interval to compute the progress by taking loaded bytes and total bytes. This might work for you.

这通过获取加载的字节和总字节来设置计算进度的间隔。这可能对你有用。