javascript - 仅在不存在但没有 document.write 的情况下加载 jQuery

标签 javascript jquery

如果不使用 document.write 的话,有什么方法可以加载 jQuery 文件吗?

<script>
   window.jQuery || document.write('<script src="/path/to/your/jquery"><\/script>');
</script>

这种方式很好,但有一个主要问题,因为如果访问者的连接速度较慢,浏览器将阻止它执行

当它发生时,我会收到此警告

file is invoked via document.write. The network request for this script MAY be blocked by the browser in this or a future page load due to poor network connectivity

我尝试了很多解决方案,但没有任何效果

最佳答案

您可以将加载回调传递给 IFFE,该回调将在脚本加载时执行,或者如果 jQuery 存在,则立即调用。

var load = function(){
  // your jQuery code goes here
  $('#hello').html('jQuery Loaded');
};

(function(window, loadCallback){
  if(!window.jQuery){
    var script = document.createElement("script");

    script.type = "text/javascript";
    script.src = "https://code.jquery.com/jquery-3.3.1.min.js";
    script.onload = loadCallback;
    
    document.head.appendChild(script);
  }else{
    loadCallback();
  }
})(window, load);
<div id="hello"></div>

关于javascript - 仅在不存在但没有 document.write 的情况下加载 jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51899365/

相关文章:

javascript - 使用jquery替换字符串

javascript - Aurelia 绑定(bind)失败不抛出错误?

javascript - 如何将div定位在中心并将其隐藏?

javascript - highcharts 中的多线图

javascript - 使用 jquery 复制 Flash 画廊

javascript - 从输入表单获取文本返回空字符串,但 console.log 显示显示文本

javascript - 尝试导入项目时出现错误 "Strict MIME type checking is enforced for module scripts per HTML spec"

javascript - 在背景图片上放置链接

javascript - 似乎无法获取 <label> 的 .html()

jquery - 在 jQuery 中显示 JSON