I have made a namespaces framework for javascript. I am loading some plugins (.js files) which are dynamically added to the HTML.
I am going to try to simplify the code.
This function is used to dinamically load a JS. The callback function is called after .js file has been loaded. Consider that the following code has already been run.
MYNAMESPACE.plugins = ["plugin1", "plugin2"];
MYNAMESPACE.getJS = {
get: function (url, callback) {
var script = document.createElement("script");
var head = document.getElementsByTagName('head')[0];
script.type = "text/javascript";
script.src = url;
head.insertBefore(script, head.firstChild)
script.onload = callback;
script.onreadystate = callback;
return script;
}
};
I have a init function that loads the plugins contained in MYNAMESPACE.plugins as follows:
MYNAMESPACE.init = function (callback) {
for (index in MYNAMESPACE.plugins) {
plugin = MYNAMESPACE.plugins[index];
MYNAMESPACE.getJS.get(plugin + '.js', function ()
{
// This callback is executed when the js file is loaded
});
}
// Here I want to execute callback function, but after all the callbacks in the for loop have been executed. Something like: if (alljsloaded) callback();
}
In my HTML I have the following script tag:
<html>
<head>
<script type="text/javascript">
$(document).ready(function () {
MYNAMESPACE.init();
// The following line is not executed correctlybecause init finished before the scripts are loaded and the functionOnPlugin1 is undefined.
MYNAMESPACE.functionOnPlugin1();
});
</script>
</head>
<body>
</body>
</html>
And I want to change it for something like this:
<html>
<head>
<script type="text/javascript">
$(document).ready(function () {
MYNAMESPACE.init(function() { MYNAMESPACE.functionOnPlugin1(); });
});
</script>
</head>
<body>
</body>
</html>
But I don't know how to modify the function MYNAMESPACE.init() so it executes the callback after ALL the plugin scripts are loaded.
Any ideas? Maybe using closures.