12-11-2011

Javascript Include once method for JavaScript

The following code mimics the php include_once functionality in that it loads / includes a certain script resource only if it has not been loaded before.

var includedOnce = {};
var includeOnce = function(src,callback){
	 if (includedOnce[src] === undefined){
		includedOnce[src] = true; 
		var newScript = document.createElement('script');
		newScript.type = 'text/javascript';
		if (callback) newScript.onload = callback;
		newScript.src = src;
		document.body.appendChild(newScript);
	 }else{
		if (callback) callback();
	 }
};
 

Comments:

Your comment:

»

 

[x]