Javascript源文件下载进度? [英] Javascript source file download progress?

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

问题描述

我正在寻找一个大的映射/小部件javascript文件(1.3 MB),并希望在加载时显示进度条。我知道firebug的网表标签知道很多这方面的信息,但我想要更轻量级的东西。我遇到过这个网站:
http://blog.greweb。 fr / 2012/04 / work-in-progress /

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/

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

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?

提前致谢!

推荐答案

如果您使用 getScript() 你可以使用成功回调来执行一个函数,但这只是在脚本加载完成后。

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

我建议加载指标图像(你可以在 http://ajaxload.info/ 上找到很多)并在脚本加载时隐藏它。

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

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

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

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.

这篇关于Javascript源文件下载进度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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