Skip to content

Instantly share code, notes, and snippets.

@mach3
Last active December 21, 2015 19:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mach3/6354968 to your computer and use it in GitHub Desktop.
Save mach3/6354968 to your computer and use it in GitHub Desktop.
harvestは根本的な不具合があったので、ローダーだけクラスにしてみた
(function(win, doc){
var Assets = function(){
this.items = [];
this.nodes = [];
this.attrs = {
callback: null,
append: true
};
};
(function(){
this.supportAsync = doc.createElement("script").async !== undefined;
this.head = doc.getElementsByTagName("head")[0];
this.items = null;
this.nodes = null;
this.count = 0;
this.callback = null;
attrs: null,
this.set = function(key, value){
this.attrs[key] = value;
};
this.add = function(files){
var my = this;
this._each(files, function(value){
my.items.push(value);
});
this.count = this.items.length;
};
this.load = function(){
var my = this;
this._each(this.items, function(url){
var el = doc.createElement("script");
my._on(el, "load", my._bind(my._process, my, el));
my._on(el, "readystatechange", my._bind(my._process, my, el));
el.type = "text/javascript";
el.src = url;
if(my.supportAsync){
el.async = false;
my.head.appendChild(el);
}
my.nodes.push(el);
});
};
this.append = function(){
var my = this;
if(! this.supportAsync){
this._each(this.nodes, function(el){
my.head.appendChild(el);
});
}
};
this._process = function(e, el){
if(el._loaded){ return; }
if(e.type === "load" || /^(complete|loaded)$/.test(el.readyState)){
el._loaded = true;
if(! -- this.count){ this._complete(); }
}
};
this._complete = function(){
var my = this;
if(! this.supportAsync && this.attrs.append){
this._each(this.nodes, function(el){
my.head.appendChild(el);
});
}
if(typeof this.attrs.callback === "function"){
this.attrs.callback(this);
}
};
this._each = function(o, callback){
for(var i in o){
if(! o.hasOwnProperty(i)){ continue; }
if(false === callback(o[i], i, o)){ break; }
}
};
this._on = function(el, name, callback){
if(el.addEventListener){ return el.addEventListener(name, callback, false); }
if(el.attachEvent){ return el.attachEvent("on" + name, callback); }
};
this._bind = function(func, obj, arg){
return function(){
var args = [].slice.call(arguments);
args.push(arg);
func.apply(obj, args);
};
};
}).call(Assets.prototype);
win.Assets = Assets;
}(window, document));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment