user441521 user441521 - 1 month ago 14
Javascript Question

Loading scripts dynamically from json config file

I have a json file that has an array of javascript files in it. I get this and then loop over each one and load each script dynamically. My question is I want to use some of the classes that were loaded dynamically after ALL the scripts have been loaded and I'm not sure how to go about knowing when they are all loaded and I can use the classes in them?

$.getJSON('Scripts/Nodes/plugins.json',
function (data) {
for (var script in data) {
$.getScript(script, function (data) {

});
}
});


Since I'm looping over scripts and loading them one at a time and each load of a script is async how do I know when ALL the scripts are loaded? This is all done on startup, so ideally after they are ALL loaded I would call a function to do what I need to do.

Answer

As Gavin said in the comments, you could leverage the success function in the getScript call. You could either increment a counter or run a function that checks if the class you wanted is defined or not, then runs the necessary code that uses that class.

You could also leverage a timeout, but I would advise against this because the timeout would be a race against the files loading, which would be unreliable. If the timeout is too long, then the user waits too long and this is a bad user experience.

Honestly you should reconsider how you're loading the javascript files. Unless you are conditionally loading the plugins, it doesn't make sense to grab the packages.json file and then loop through the packages. Just include all your packages on the page, or better yet, concatenate and minify your packages into one 'core.js' file. There are a variety of NPM/Grunt/JSPM tools to do this for you.