首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >有没有什么建议用自动执行函数来动态添加jQuery?

有没有什么建议用自动执行函数来动态添加jQuery?
EN

Stack Overflow用户
提问于 2021-09-17 18:01:44
回答 2查看 34关注 0票数 0

我想在JS文件中动态导入jQuery。下面是我的代码:

代码语言:javascript
复制
(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")
  });
})();
EN

回答 2

Stack Overflow用户

发布于 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")
  • Also在头部添加一个类来检查脚本是否加载可能不是最好的方法,如果要执行此操作,请将类或数据属性添加到附加script元素中。variable.
  • $(document).ready(function() {
  • 如果您已经有DOM,为什么还要使用head查询它?variable.
  • $(document).ready(function() {会尝试将带有内容script的测试字符串附加到EnScript中,而不是将您创建并存储在script中的元素附加到.ready(中,因为当您动态加载jQuery时,也没有多大意义,因为DOM已经被读取。H229F230

这就是加载脚本的方式:

代码语言:javascript
复制
(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);

})();

票数 0
EN

Stack Overflow用户

发布于 2021-09-17 18:38:57

有一些错误,您正在检查head是否有类"En-Script",然后将类添加到head,所以我更改了验证,以便它有意义。然后,使用querySelector选择头部,只返回1个值,并使用[0],如果使用querySelectorAll,这将起作用。

然后,您应该在脚本加载之后添加jquery函数$(document),所以我添加了一个script.onload来实现这一点。

另外,当你追加一个子对象时,你应该发送你创建的对象,而不是一个字符串,所以我用head.appendChild(script);代替了这个EnScript.appendChild("script");

代码语言:javascript
复制
(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");
  }


})();

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69227777

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档