0

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.

KuKu
  • 646
  • 2
  • 15
  • 38

2 Answers2

0

Take a look at jQuery's .load() http://api.jquery.com/load-event/

$('script').load(function () { }); 
Sridhar R
  • 20,190
  • 6
  • 38
  • 35
  • This method is deprecated as of Jquery1.8. The "on" method must be used instead http://api.jquery.com/on/ – eggward Oct 25 '13 at 05:15
0

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.

eggward
  • 345
  • 1
  • 5