简体   繁体   中英

Loading javascript files in js files. Which is best way to check whether all files are loaded or not?

I have a array where i have specified the files i need to load in javascript before calling specific script. Lets call those particular lines of code as myscript .

I did as follows

var fileNamesArray = new Array();
    fileNamesArray.push("abc.js");
    fileNamesArray.push("pqr.js");
    fileNamesArray.push("xyz.js");
    fileNamesArray.push("klm.js");

    var totalFiles = jQuery(fileNamesArray).length;
    var tempCount = 0;

    jQuery.each(fileNamesArray, function(key, value) {
        jQuery.getScript(value, function() {
            tempCount++;
        });
    });

to check whether all files are being loaded or not, i done following thing but doesn't seems to be effective

var refreshIntervalId = setInterval(function() {
        if (tempCount == totalFiles) {
            clearInterval(refreshIntervalId);
            return;
        }
    }, 10);

i have implemented these in object oriented javascript as follows

function Loader() {

    this.jQuery = null;

    // check for specifically jQuery 1.8.2+, if not, load it

    if (jQuery == undefined) {
        jQuery.getScript(
                "/Common/javascript/jquery/map/javascript/jquery-1.8.2.js",
                function() {
                    this.jQuery = jQuery.noConflict();
                });
    } else {
        var jQueryVersion = $.fn.jquery;

        jQueryVersion = parseInt(jQueryVersion.split('.').join(""));

        if (182 > jQueryVersion) {
            jQuery.getScript(
                    "/Common/javascript/jquery/map/javascript/jquery-1.8.2.js",
                    function() {
                        this.jQuery = jQuery.noConflict();
                    });
        }
    }
}

Loader.prototype.LoadAllFile = function() {
//here i am loading all files
}

Loader.prototype.bindMap = function(options) {
this.LoadAllFile();
//execute the script after loading the files... which we called as myscript
}

i am loading more than 12-14 js files via ajax.

if you observe Loader.prototype.bindMap , i am loading all the files first and then executing the script.

But it seems that myscript the script start executing before all files being loaded.

what are the better ways to execute the script only after all js files are loaded.

看看jQuery的.load() http://api.jquery.com/load-event/

$('script').load(function () { }); 

Based on the documentation on Jquery.getScript , it is a shorthand for Jquery.ajax. By default this in async call. You might want to change it to do a synchronous call. To set this property, you can refer to this

So instead of doing a setInterval, you can just loop in your array and do a Jquery.getScript.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM