话不多说,直接上源码,用了传说中的伪面向对象写法
加了个jsonp
用来跨域,当然了,需要服务端支持才有效
(function(){
var WT = {
ID_SEL:'#',
CLA_SEL:'.',
newInstance:function(){
var instance = {};
var setAttrs = function (dom,attrs){
for(var key in attrs){
dom.setAttribute(key,attrs[key]);
}
}
var convertParam = function(data){
var param = [];
for (var key in data) {
param.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
}
return param;
}
instance.select = function(selector){
var h = selector.charAt(0);
var o = null;
var m = null;
if(h==WT.ID_SEL){
m = selector.substr(1);
o = document.getElementById(m);
}
else if(h==WT.CLA_SEL){
//TODO
//m = selector.substr(1);
//o = document.getElementsByClassName(m);
}else {
m = selector;
o = document.getElementsByTagName(m);
}
return o;
}
instance.load = function(tagName, attrs, callback){
var dom = document.createElement(tagName);
setAttrs(dom,attrs);
dom.onload=function(){
typeof callback === 'function' && callback.call(this,dom);
dom = null; callback =null;
}
return dom;
}
instance.jsonp = function(jp){
//---- attributes----//
var callback = jp.callback;
var url = jp.url;
var data = jp.data;
var cn = 'jsonp'+ Date.now();
window[cn] = callback;
var param = convertParam(data);
param.push('callback=' + cn);
url += (url.indexOf('?')==-1 ? '?' : '') + param.join('&');
var script = document.createElement('script');
script.type = 'text/javascript';
script.onload = script.onreadystatechange = function() {
this.parentNode.removeChild(script);
delete window[cn];
script.onload = script.onreadystatechange = null;
}
script.src = url;
this.select('body')[0].appendChild(script);
}
instance.ajax = function(jp){
//---- attributes----//
var type = jp.type;type ? type : 'GET';
var url = jp.url;
var data = jp.data;
var success = jp.success;
var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xhr.open(type,url);
if (type.toUpperCase() === 'POST') {
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
xhr.onreadystatechange = function(){
if(xhr.readyState==4){
typeof success === 'function' && success(eval('(' + xhr.responseText + ')'), xhr.status);
xhr = null;
}
}
xhr.send(convertParam(data).join('&'));
}
instance.loadImg = function (url, callback) {
/** img的onload在图片下载完成后,dom加载前发生 **/
this.load('img',{src:url},callback);
}
instance.loadCss = function(url,callback){
/** css的onload 在 dom加载后发生 **/
var dom = this.load('link',{rel:'stylesheet',type:'text/css',href:url},callback);
this.select('head')[0].appendChild(dom);
}
instance.loadJs = function(url,callback){
/** js的onload 在 dom加载后发生 **/
var js = this.load('script',{type:'text/javascript',src:url},callback);
this.select('body')[0].appendChild(js);
}
return instance;
}
};
window['$'] = WT.newInstance();
})();