的情况下在 Javascript 中包含 jQuery 库-6ren"> 的情况下在 Javascript 中包含 jQuery 库-我需要在 javascript 文件 (john.js) 中远程包含 jQuery 库。我已经尝试过了,但没有任何运气; (function(d, t) { var g = d.createE-6ren">
gpt4 book ai didi

javascript - 如何在没有 <script src =""> 的情况下在 Javascript 中包含 jQuery 库

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:04:33 25 4
gpt4 key购买 nike

我需要在 javascript 文件 (john.js) 中远程包含 jQuery 库。我已经尝试过了,但没有任何运气;

(function(d, t) {
var g = d.createElement(t), // create a script tag
s = d.getElementsByTagName(t)[0]; // find the first script tag in the document
g.src = 'http://code.jquery.com/jquery-latest.js'; // set the source of the script to your script
s.parentNode.insertBefore(g, s); // append the script to the DOM
}(document, 'script'));

$( document ).ready(function() {

// My jquery works here

});

我想以 javascript 方式获取脚本。正确的做法是什么?

最佳答案

这里的错误是执行这段代码时JQuery还没有加载:

$(document).ready(function() { .. }

照原样,你会得到这样的错误:$ is undefined(或类似的)

您应该使用创建的脚本元素的 onload 事件来确保它已加载 Jquery。

此示例展示了如何实现您的目标。祝你好运。

var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = 'http://code.jquery.com/jquery-latest.js'; // set the source of the script to your script
newScript.onload = function() {
alert("Script is ready!");
$(document).ready(function() {
alert("JQuery is ready!");
});
};
var head = document.getElementsByTagName("head")[0];
head.appendChild(newScript);

关于javascript - 如何在没有 &lt;script src =""> 的情况下在 Javascript 中包含 jQuery 库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27327904/

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