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'];
			newscript.onload = function(){ require(libs, callback); };
		}else if(typeof(callback)!='undefined'){  
			newscript.onload = callback;
                 require(libs, callback);

		{'lib':'jQuery', 'script':''}, 
		{'lib':'jQuery.fn.flash', 'script':''}
		], function(){ 
	window.alert("jQuery not defined");
	window.alert("jQuery defined");

   	window.alert("jQuery.flash not defined");
	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="" 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! :)