繁体   English   中英

如何使用javascript动态添加脚本标签并检测脚本是否无法加载文件?

[英]How to add a script tag dynamically using javascript and detect if the script failed to load the file?

我知道如何使用附加功能将脚本标签添加到身体或头部。 但是,如果我尝试添加的文件(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>'); } 

我认为您可以执行以下操作:

  script = document.createElement('script');
  script.type = 'text/javascript';
  script.onerror = () => {
    // Whatever you want to do in case the load fails
  };
  script.src = '...' // your src for the script

  // After this, append the script to wherever you want in the HTML document

希望能帮助到你!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM