我想在JS文件中动态导入jQuery。下面是我的代码:
(function() {
var head = document.querySelector("head")[0];
if (head.classList.contains("En-Script") == true) {
head.classList.add("En-Script");
var script = document.createElement("SCRIPT");
let EnScript = document.querySelector(".En-Script");
script.type = "text/javascript";
script.src = "./jquery-3.6.0.min.js";
EnScript.appendChild("script");
} else {
console.log("class_list_added_for_further_process");
}
$(document).ready(function() {
console.log("jquery added successfully")
});
})();发布于 2021-09-17 18:38:49
您的代码中存在各种问题。
querySelector返回一个元素,而不是数组,所以document.querySelector("head")[0]没有任何意义。if (head.classList.contains("En-Script") == true) {测试head是否有En-Script类,这与head.classList.add("En-Script")script元素中。variable.$(document).ready(function() { head查询它?variable.$(document).ready(function() {会尝试将带有内容script的测试字符串附加到EnScript中,而不是将您创建并存储在script中的元素附加到.ready(中,因为当您动态加载jQuery时,也没有多大意义,因为DOM已经被读取。H229F230这就是加载脚本的方式:
(function() {
var head = document.querySelector("head");
var script = document.createElement("script");
script.type = "text/javascript";
script.onload = function() {
// called when the script is loaded and ready to use
console.log("jquery added successfully")
}
script.src = "https://code.jquery.com/jquery-3.6.0.slim.min.js";
head.appendChild(script);
})();
发布于 2021-09-17 18:38:57
有一些错误,您正在检查head是否有类"En-Script",然后将类添加到head,所以我更改了验证,以便它有意义。然后,使用querySelector选择头部,只返回1个值,并使用[0],如果使用querySelectorAll,这将起作用。
然后,您应该在脚本加载之后添加jquery函数$(document),所以我添加了一个script.onload来实现这一点。
另外,当你追加一个子对象时,你应该发送你创建的对象,而不是一个字符串,所以我用head.appendChild(script);代替了这个EnScript.appendChild("script");
(function() {
var head = document.querySelector("head");
if (!head.classList.contains("En-Script")) {
head.classList.add("En-Script");
var script = document.createElement('script');
script.type = "text/javascript";
script.src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js";
script.onload = function() {
$(document).ready(function() {
console.log("jquery added successfully")
});
};
head.appendChild(script);
} else {
console.log("class_list_added_for_further_process");
}
})();
https://stackoverflow.com/questions/69227777
复制相似问题