// 动态加载js
loadJS( url, callback ){
let fn = () => {
if (typeof callback === 'function') {
callback();
}
};
// 获取head标签,并在head标签里插入新的script标签
let head = document.getElementsByTagName('head')[0];
let srcArr = document.getElementsByTagName("script");
let hasLoaded = false;
for (let i=0;i<srcArr.length;i++){ // 判断当前js是否加载上
hasLoaded = (srcArr[i].src === url)?true:false;
}
if (hasLoaded) {
fn();
return;
}
let js = document.createElement('script');
js.setAttribute('type', 'text/javascript');
//IE
if(document.all){
js.onreadystatechange = function(){
if( js.readyState == 'loaded' || js.readyState == 'complete' ){
js.onreadystatechange = null;
fn();
}
};
}else{
//其他浏览器
js.onload = function(){
fn();
};
js.onerror = () => {
console.log('动态加载js出错')
}
}
js.setAttribute('src', url);
head.appendChild(js);
}