jitScript – safe load external javascript , prevent duplicate

snipplr

var regJs = "";
var JitScriptDebug = false;

var kaizekuJitScript = {
  src: function(){ kaizekuJitScript.jitScript(this);},
  jitScript: function(src){
  var iArray = (src instanceof Array) ? src : src.split(/s*,s*/) ;
  for (i = 0; m = iArray.length, i < m; i++){
	var uri = iArray[i];
	  if (regJs.indexOf(uri) ==- 1) {
		var s = document.createElement('script');
		s.src = uri;
		if (s instanceof Object){
			try{
			document.body.appendChild(s);
			} catch(e){
				document.write('<script type="text/javascript" src="'+uri+'"><\/script>');
			}
	  	}
			regJs += uri + "|";
		} else {
			if (JitScriptDebug){
				kaizekuJitScript.fireBuglog("Reject duplicated entries: %s",uri);
				kaizekuJitScript.displayloadedJS();
			}
		}
	}
},
isJsLoad: function(){
	var iArray = (this instanceof Array) ? this : this.split(/s*,s*/) ;
	var d = regJs;
	for (i = 0; m = iArray.length, i < m; i++){
		var n = iArray[i];
		var r = (d.indexOf(n) ==- 1) ? false : true;
		if (JitScriptDebug) kaizekuJitScript.fireBuglog(n + " %s",r);
		return r;
	}
},
fireBuglog:function(str,ref){ if(typeof console != "undefine") { console.log(str,ref)} },

displayloadedJS:function(display){
	var ln = 'Loaded script\n', js = regJs.split("|");
	for(var i =0; i < (js.length - 1 ); i++){
		var str = '('+(i+1)+') : ' + js[i] + '\n';	ln += str;
	}
	( (display == false ) ? alert(ln) : kaizekuJitScript.fireBuglog("%s",ln) );
}
};

Array.prototype.jitScript = kaizekuJitScript.src;
String.prototype.jitScript = kaizekuJitScript.src;
Array.prototype.isLoadJs = kaizekuJitScript.isJsLoad;
String.prototype.isLoadJs = kaizekuJitScript.isJsLoad;

Example

var lib = ['foo.js','foo.js','foo2.js','foo.js','foo333.js','foo2.js'];
var slib = 'fooooo.js';

lib.jitScript(); // append foo.js, foo2.js & foo33.js
slib.jitScript(); // append fooooo.js

enable firebug console
JitScriptDebug = true;

validate scripts
lib.isJsLoad(); //return bool
some real live example can be found here view source output.js

Advertisements

Leave a comment

Filed under javascript

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s