//方法一
function loadScript(option) {
var scriptList=option.scriptList;
var callback=option.callback;
var index=option.index;
var async=option.async;
if (scriptList instanceof Array) {
index=typeof(index)=="number"?index:0;
if (index<scriptList.length) {
var xmlHttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlHttp = new XMLHttpRequest();
} else {
try {
//IE6以及以后版本中可以使用
xmlHttp = new ActiveXObject("Msxml2.xmlHttp");
}
catch (e) {
//IE5.5以及以后版本可以使用
xmlHttp = new ActiveXObject("Microsoft.xmlHttp");
}
}
var scriptUrl=scriptList[index];
console.log("【"+index+"】"+scriptUrl);
xmlHttp.open("GET",scriptUrl,(async===false?async:true));
xmlHttp.send();
xmlHttp.onreadystatechange=function(){
if (xmlHttp.readyState==4)
{
//0为访问的本地,200到300代表访问服务器成功,304代表没做修改访问的是缓存
if((xmlHttp.status >= 200 && xmlHttp.status <300) || xmlHttp.status == 0 || xmlHttp.status == 304){
console.log('下载文件成功!');
if(callback(scriptUrl,xmlHttp)){
//添加script标签
var myScript = document.createElement("script");
myScript.type = "text/javascript";
try{
//IE8以及以下不支持这种方式,需要通过text属性来设置
myScript.appendChild(document.createTextNode(xmlHttp.responseText));
}
catch (ex){
myScript.text = xmlHttp.responseText;
}
document.body.appendChild(myScript);
loadScript({
"scriptList":scriptList
,"callback":callback
,"index":++index
,"async":async
});
}else {
console.log('停止加载。。。');
}
}else {
console.log('['+xmlHttp.status+']加载文件失败!');
}
}
}
xmlHttp.οnerrοr=function(){
console.log('加载文件失败!');
}
xmlHttp.ontimeout=function(){
console.log('加载文件超时-->'+scriptList[i]);
}
}
}else {
alert("js 列表为空!");
}
}
//方法二
function loadScript2(option) {
var scriptList=option.scriptList;
var callback=option.callback;
var index=option.index;
var async=option.async;
if (scriptList instanceof Array) {
index=typeof(index)=="number"?index:0;
if (index<scriptList.length) {
var scriptUrl=scriptList[index];
var myScript = document.createElement("script");
myScript.type = "text/javascript";
myScript.src=scriptUrl;
myScript.defer=myScript.async=(async===false?async:true);
myScript.onload = myScript.onreadystatechange=function(){
if(!this.readyState //这是FF的判断语句,因为ff下没有readyState这人值,IE的readyState肯定有值
|| this.readyState=='loaded' || this.readyState=='complete' // 这是IE的判断语句
){
if (callback(index,scriptUrl)) {
loadScript2({
"scriptList":scriptList
,"callback":callback
,"index":++index
,"async":async
});
}
}
}
document.body.appendChild(myScript);
}
}else {
alert("js 列表为空!");
}
}
(function() {
var timeStamp=new Date().getTime()/30000;
// timeStamp=0;
var scriptList=[
'js/jquery-1.9.1.min.js?_='+timeStamp
];
// loadScript({
// "scriptList":scriptList
// ,"async":true
// ,"callback":function(scriptUrl,xmlHttp){
// return true;
// }
// });
loadScript2({
"scriptList":scriptList
,"async":true
,"callback":function(index,scriptUrl){
console.log("【"+index+"】"+scriptUrl);
return true;
}
});
})();