I am appending the jQuery library to the dom using:

 var script = document.createElement('script');
 script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';
 script.type = 'text/javascript';
 document.getElementsByTagName('head')[0].appendChild(script);

但是,当我 run 时:

jQuery(document).ready(function(){...

The console reports the error:

Uncaught ReferenceError: jQuery is not defined

How do I load jQuery dynamically as well as use it once it is in the dom?

推荐答案

There's a working JSFiddle with a small example here, that demonstrates exactly what you are looking for (unless I've misunderstood your request): http://jsfiddle.net/9N7Z2/188/

There are a few issues with that method of loading javascript dynamically. When it comes to the very basal frameworks, like jQuery, you actually probably want to load them statically, because otherwise, you would have to write a whole JavaScript loading framework...

您可以使用一些现有的JavaScript加载程序,或者通过观察window.jQuery来定义自己的JavaScript加载程序.

// Immediately-invoked function expression
(function() {
  // Load the script
  const script = document.createElement("script");
  script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js';
  script.type = 'text/javascript';
  script.addEventListener('load', () => {
    console.log(`jQuery ${$.fn.jquery} has been loaded successfully!`);
    // use jQuery below
  });
  document.head.appendChild(script);
})();

请记住,如果您需要支持104个旧浏览器(如IE8),load事件处理程序不会执行.在这种情况下,您需要使用重复的window.setTimeout轮询window.jQuery是否存在.这里有一个可以使用该方法的JSFdle:http://jsfiddle.net/9N7Z2/3/

有很多人已经做了你需要做的事情.查看一些现有的JavaScript加载程序框架,如:

  • https://developers.google.com/loader/(不再记录)
  • http://yepnopejs.com/(已弃用)
  • http://requirejs.org/

Jquery相关问答推荐

将搜索面板和服务器端与POST AJAX请求一起使用时出现DataTables错误

使用带有 Ajax GET URL 的数组在每次单击按钮时一次单步执行一个

在文本框中的最后一个字符之后设置焦点

在 for 循环中分配点击处理程序

是否可以使用 javascript 打开一个弹出窗口,然后检测用户何时关闭它?

Google Maps API v3 infowindow 关闭事件/回调?

在 contenteditable div 中的插入符号处插入 html

如何在jQuery中 Select 具有特定ID的所有元素?

javascript:检测滚动结束

jquery click 不适用于 ajax 生成的内容

从 iframe 访问父窗口的元素

如何使用 jQuery 显示忙碌指示器?

在不使用提交按钮的情况下触发标准 HTML5 验证(表单)?

未捕获的语法错误:无法在文档上执行querySelector

根据弹出框相对于窗口边缘的 X 位置更改 Bootstrap 弹出框的位置?

使用 jQuery 从 AJAX 响应(json)构建表行

为不同的 node 类型配置jstree右键上下文菜单

使用 Typescript 时如何停止类型 JQuery 上不存在属性语法错误?

由于滚动,响应表内的 bootstrap 按钮下拉菜单不可见

组织 jQuery/JavaScript 代码的最佳方式 (2013)