我知道如何使用附加函数将脚本标记添加到正文或头部。但是,如果我尝试添加的文件(example.js)不存在,则会出现错误。如何检测是否发生这种情况?
最佳答案
脚本元素具有您可以监听的加载和错误事件。
在加载事件处理程序中运行您的依赖代码,并在错误处理程序中执行其他操作
加载 jQuery 的示例:
var jQurl='https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'
var s = document.createElement('script');
s.src = jQurl;
s.onerror = function(err) {
console.log(err)
}
s.onload = init;
document.head.appendChild(s);
function init(){
console.log('jquery version=', jQuery.fn.jquery)
$('body').append('<h3>Loaded!</h3>');
}
关于javascript - 如何使用javascript动态添加脚本标签并检测脚本是否无法加载文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48452886/