Javascript: How to check dependencies and load missed libraries. JQuery example.

Sometimes we are distributng javascript libraries that have some dependencies. Here I want to show how to check loaded and load missed ones. This problem has a few aspects worth mentioning. First of all libraries can depend from each other (like in my example when jQuery.flash requires jQuery to be loaded), so load order is important. The other important thing is that execution of the code that requires the libraries should be started only when the libraries are loaded.

To solve this problem I decided to use recursion through the list of the libraries. If library is loaded next recursion step is executed imidietely, if library is not loaded than next recursion step is executed on script load event. This allows to ensure that previous script is loaded.

So here is the code, so you will be able to see everything yourself. I believe that the best documentation and description of the program code is the actual code.

function require(libs, callback){
	var el = libs.shift();
	if (typeof(window[el['lib']]) != 'function') {
		var newscript = document.createElement('script');
		newscript.type = 'text/javascript';
		newscript.src = el['script'];
		if(libs.length>0){
			newscript.onload = function(){ require(libs, callback); };
		}else if(typeof(callback)!='undefined'){  
			newscript.onload = callback;
		}
		(document.getElementsByTagName('head')[0]||document.getElementsByTagName('body')[0]).appendChild(newscript);
	}else{
                 require(libs, callback);
        }
}

require([
		{'lib':'jQuery', 'script':'http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'}, 
		{'lib':'jQuery.fn.flash', 'script':'http://yourdomain.com/js/jquery.flash.js'}
		], function(){ 
		
if(typeof(jQuery)=='undefined'){
	window.alert("jQuery not defined");
}else{
	window.alert("jQuery defined");
}

if(typeof(jQuery.fn.flash)=='undefined'){
   	window.alert("jQuery.flash not defined");
}else{
	window.alert("jQuery.flash defined");
}
			
});
}

As you can see executing the code both libraries will be loaded. To test the situation when one of the libraries are already loaded you may load jQuery javascript library from google before the code.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>

Please, let me know if you can see some better solution for that problem or if I miss something. In this article I am not touching versioning as it is not important for me now, but may be I will write an article about it soon, so follow my blog.

Posted by:
Enjoyed this post? Share and Leave a comment below, thanks! :)