본문으로 바로가기

스크립트 순서대로 로딩하기[펌]

category JS/JavaScript 2015. 9. 25. 15:57

아래와 같이 추가

function getScripts( scripts, onScript, onComplete )
{
this.async = true;
this.cache = false;
this.data = null;
this.complete = function () { $.scriptHandler.loaded(); };
this.scripts = scripts;
this.onScript = onScript;
this.onComplete = onComplete;
this.total = scripts.length;
this.progress = 0;
};

getScripts.prototype.fetch = function() {
$.scriptHandler = this;
var src = this.scripts[ this.progress ];
//console.log('%cFetching %s','color:#ffbc2e;', src);

$.ajax({
crossDomain:true,
async:this.async,
cache:this.cache,
type:'GET',
url: src,
data:this.data,
statusCode: {
200: this.complete
},
dataType:'script'
});
};
getScripts.prototype.loaded = function () {
this.progress++;
if( this.progress >= this.total ) {
if(this.onComplete) this.onComplete();
} else {
this.fetch();
};
if(this.onScript) this.onScript();
};

사용방법 : 아래 처럼 인스턴스를 생성하고 .fetch()로 실행 한다.

순서대로 스크립트를 로딩 시키기 때문에 순서를 지킬 필요가 있는 상황에서 유용하다.

var scripts = new getScripts(
['script1.js','script2.js'],
function() {
//부분 완료 콜백
},
function () {
//전체 로딩 완료 콜백
}
);

scripts.fetch();