gpt4 book ai didi

javascript - 如果 .js 文件不存在,则包含 jQuery

转载 作者:行者123 更新时间:2023-12-01 00:56:23 24 4
gpt4 key购买 nike

我正在创建一个库,如果用户的 HTML 文件中未包含 jQuery,我希望将其包含在内。

下面的链接中有一些建议:

How to add jQuery in JS file

但是,我不知道为什么它不起作用。

以下是 HTML 和 .js 代码:

 document.head.innerHTML += "<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script>";
<!DOCTYPE html>
<html>
<head>
<script src="mydebugger.js"></script>
</head>
<body>
<div></div>
<script>
$("div").html("Hi");
console.log(document);
</script>
</body>
</html>

通过控制台可以看到<script>添加到<head>但它就是行不通。

请考虑一下,我只能从 .js 文件添加 jQuery,而无法将其直接添加到 HTML 文件中。

最佳答案

这是一个我认为非常适合您的解决方案:

// This will check if jQuery has loaded. If not, it will add to <head>
window.onload = function() {
if (!window.jQuery) {
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://code.jquery.com/jquery-latest.min.js';
head.appendChild(script);
}
}

// This will wait until Jquery is loaded then fire your logic
defer(function () {
$("div").html("Hi");
console.log(document);
});


function defer(method) {
if (window.jQuery) {
method();
} else {
setTimeout(function() { defer(method) }, 50);
}
}
<!DOCTYPE html>
<html>
<head>
<script src="mydebugger.js"></script>
</head>
<body>
<div></div>
</body>
</html>

关于javascript - 如果 .js 文件不存在,则包含 jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56552131/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com