有时候为了避免引入插件过多,需要在代码中根据逻辑判断是否需要引入插件,并运行插件的方法,下面介绍一下使用方式:
if(location.hostname!=='www.baidu.com'&&location.hostname!=='180.101.50.242'){
var script = document.createElement('script');
script.src = '/libs/vconsole.min.js';//也可以是http://www.xxx.cn/xxx.js
document.head.appendChild(script);
//下面这两种方式选一种即可,推荐第一种
//方式一
setTimeout(function(){new VConsole();}, 500);//需要定时才可以加载完vconsole插件
//方式二
setTimeout(() => {
var jsContent = document.createElement('script');
jsContent.textContent = 'new VConsole();';
document.head.appendChild(jsContent);
}, 500);
}
//方式一优化:可以用递归判断VConsole是否存在再实例化VConsole
var num=0
function fn(duration){
if(window.VConsole){
new VConsole();
num=null;
}else{
setTimeout(() => {
num++
if(num<10*1000/duration){ //10秒钟之内递归
fn(duration);
}else{
num=null
}
}, duration);
}
}
fn(200)