Tuesday, September 13, 2011

Random nifty tidbit for javascript - I find stuff like this all over the web, "How do you do X" and they show you a very direct very simple not useful quip - I'm fixing this - how to include javascript files from javascript the right way.
function include(urls, cb) {
	var loaded = {};
	for (i in urls) {
		loaded[urls[i]] = false;
	}
	
	for (i in urls) {
		(function(i) {
			var url = urls[i];
			var head = document.getElementsByTagName("head")[0];
			var script = document.createElement('script');
			script.src = url;
			script.type = 'text/javascript';
			script.src = url;
			script.onload = function() {
				loaded[url] = true;
				var done = true
				for (x in loaded)
					done = done && loaded[x];

				if (done) {
					cb();
				}
			}
			head.appendChild(script);
		})(i)
	}
}

there, fixed - you used it like this
include(['http://ajax.googleapis.com/ajax/libs/jquery/1.6.3/jquery.min.js'], function() {
	jQuery(function($) {
		// Use it all here like normal
	});
});
Read more...