jquery 활용 js 파일 include 하기

js API/jquery 2012. 4. 3. 15:55

jquery 활용 js 파일 include 하기


jquery를 이용해 js 파일들을 인클루드 하는 플러그인을 소개할까 합니다.
정말 유용한데요

먼저 include 해야할 js 파일을 한 후
순차적으로 js 파일을 인클루드 할 수 있도록 되어있습니다.

물론 jQuery 를 활용하기 때문에 jQuery는 먼저 불어 와 있어야 하겠죠? ^^



1. 기본환경설정
< script src="/common/js/jquery-1.7.1.min.js" >< /script >
< script src="/common/js/jquery.extended.js" >< /script >


2. 사용법
# 방법 1  /=========================
$.include(
	'js/my.js',
	// my.js 로딩 후 my1.js 를 로딩함
	$.include('js/my1.js')
);

# 방법 2 /==============================
$.include('js/my.js',
	// my.js를 먼저 로딩 후 my1.js, my2.js 를 불러 들입니다.
	[
		$.include('js/src/my1.js'),
		$.include('js/src/my2.js')
	]
);



@ jquery.extended.js 소스 /================
/**
 * $.include - script inclusion jQuery plugin
 * Based on idea from http://www.gnucitizen.org/projects/jquery-include/
 * @author Tobiasz Cudnik
 * @link http://meta20.net/.include_script_inclusion_jQuery_plugin
 * @license MIT
 */
// overload jquery's onDomReady
if ( jQuery.browser.mozilla || jQuery.browser.opera ) {
	document.removeEventListener( "DOMContentLoaded", jQuery.ready, false );
	document.addEventListener( "DOMContentLoaded", function(){ jQuery.ready(); }, false );
}
jQuery.event.remove( window, "load", jQuery.ready );
jQuery.event.add( window, "load", function(){ jQuery.ready(); } );
jQuery.extend({
	includeStates: {},
	include: function(url, callback, dependency){
		if ( typeof callback != 'function' && ! dependency ) {
			dependency = callback;
			callback = null;
		}
		url = url.replace('\n', '');
		jQuery.includeStates[url] = false;
		var script = document.createElement('script');
		script.type = 'text/javascript';
		script.onload = function () {
			jQuery.includeStates[url] = true;
			if ( callback )
				callback.call(script);
		};
		script.onreadystatechange = function () {
			if ( this.readyState != "complete" && this.readyState != "loaded" ) return;
			jQuery.includeStates[url] = true;
			if ( callback )
				callback.call(script);
		};
		script.src = url;
		if ( dependency ) {
			if ( dependency.constructor != Array )
				dependency = [dependency];
			setTimeout(function(){
				var valid = true;
				$.each(dependency, function(k, v){
					if (! v() ) {
						valid = false;
						return false;
					}
				})
				if ( valid )
					document.getElementsByTagName('head')[0].appendChild(script);
				else
					setTimeout(arguments.callee, 10);
			}, 10);
		}
		else
			document.getElementsByTagName('head')[0].appendChild(script);
		return function(){
			return jQuery.includeStates[url];
		}
	},
	readyOld: jQuery.ready,
	ready: function () {
		if (jQuery.isReady) return;
		imReady = true;
		$.each(jQuery.includeStates, function(url, state) {
			if (! state)
				return imReady = false;
		});
		if (imReady) {
			jQuery.readyOld.apply(jQuery, arguments);
		} else {
			setTimeout(arguments.callee, 10);
		}
	}
});