Javascript 如何知道外部js是否已加载,并在此之前放置百分比加载程序

Javascript 如何知道外部js是否已加载,并在此之前放置百分比加载程序,javascript,jquery,Javascript,Jquery,我正在使用$.getScripturl加载外部js。现在,在加载js之前,我希望百分比加载器显示加载了多少js。我该怎么做呢 $(document).on('click', 'div#play', function(){ $(this).hide(); $('div#stop').css('display', 'block'); $('div#processing_load').show(); var url = 'https://

我正在使用$.getScripturl加载外部js。现在,在加载js之前,我希望百分比加载器显示加载了多少js。我该怎么做呢

$(document).on('click', 'div#play', function(){
        $(this).hide();
        $('div#stop').css('display', 'block');
        $('div#processing_load').show();
        var url = 'https://www.gstatic.com/swiffy/v5.4/runtime.js';
        $.getScript(url)
            .done(function(){
                $('div#processing_load').hide();
                $('#swiffycontainer').css('display', 'block');
                $('.landing-banner').css('display', 'none');

                stage = new swiffy.Stage(document.getElementById('swiffycontainer'), swiffyobject);
                stage.start();
                stage.setBackground(null); 
            })
    })

在这里,我想显示加载之前完成的百分比。提前感谢。欢迎您提供任何帮助/建议。

我想您不能完全按照进度条来做 为什么?因为我们不知道装载完成的时间

但您可以使用一些提示来显示progressbar: 您需要知道文件大小,并可以计算互联网速度

time to load  = your file size / your internet speed ;
  => show progress bar when you begin to load .
计算可基于的速度

连接类型2G、3G、WiFi、有线=>获取其速度 计算加载时的速度连接。你可以在网上阅读更多http://stackoverflow.com/questions/4583395/calculate-speed-using-javascript 使用导航计时API:window.performance*
最后,现在可以使用依赖于网络的进度条精确显示

使用更强大的ajax而不是getScript。它还允许您解析数据以设置加载状态,我编辑了未经测试的代码:

$.ajax({
    xhr: function () {
        var xhr = new window.XMLHttpRequest();
        xhr.addEventListener("progress", function (evt) {
        //check if the length of the requested file is computable (if you generate the requested file using php, you require ob_start(); and ob_end_flush();)
            if (evt.lengthComputable) {
                //Calculate the percentage completed
                var percentComplete = Math.floor((evt.loaded / evt.total) * 100) + '%';
                //Do something with download progress
                $('div#processing_load').show().html(percentComplete);
            }
        }, false);
        return xhr;
    },
    url: 'https://www.gstatic.com/swiffy/v5.4/runtime.js',
    dataType: 'script',
    complete: function(xhr) {
        //you can use the xhr object to check for response codes 
        $('div#processing_load').hide();
        $('#swiffycontainer').css('display', 'block');
        $('.landing-banner').css('display', 'none');

        var stage = new swiffy.Stage(document.getElementById('swiffycontainer'), swiffyobject);
        stage.start();
        stage.setBackground(null);
    }
});