如果不使用 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/