Javascript source file download progress?

前端 未结 1 1633
逝去的感伤
逝去的感伤 2020-12-03 16:54

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 informati

相关标签:
1条回答
  • 2020-12-03 17:09

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

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

    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.

    0 讨论(0)
提交回复
热议问题