使用Javascript加载jQuery并使用jQuery [英] Load jQuery with Javascript and use jQuery
问题描述
我使用以下命令将jQuery库附加到dom:
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);
但是当我跑步时:
jQuery(document).ready(function(){...
控制台报告错误:
Uncaught ReferenceError: jQuery is not defined
我如何动态加载jQuery以及在dom中使用它?
How do I load jQuery dynamically as well as use it once it is in the dom?
推荐答案
这里有一个工作的JSFiddle,其中有一个小例子,它可以准确地显示您正在寻找的内容(除非我误解了您的请求): http://jsfiddle.net/9N7Z2/188/
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/
这种动态加载javascript的方法存在一些问题。当谈到非常基础的框架时,比如jQuery,你实际上可能想要静态加载它们,因为否则,你必须编写一个完整的JavaScript加载框架......
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加载器。
You could use some of the existing JavaScript loaders, or write your own by watching for window.jQuery
to get defined.
// Immediately-invoked function expression
(function() {
// Load the script
var script = document.createElement("SCRIPT");
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';
script.type = 'text/javascript';
script.onload = function() {
var $ = window.jQuery;
// Use $ here...
};
document.getElementsByTagName("head")[0].appendChild(script);
})();
请记住,如果你需要支持 真的 旧浏览器,如IE8,加载
事件处理程序不执行。在这种情况下,您需要使用重复的 window.setTimeout
轮询 window.jQuery
的存在。这里有一个有效的JSFiddle: http://jsfiddle.net/9N7Z2/3/
Just remember that if you need to support really old browsers, like IE8, load
event handlers do not execute. In that case, you would need to poll for the existance of window.jQuery
using repeated window.setTimeout
. There is a working JSFiddle with that method here: http://jsfiddle.net/9N7Z2/3/
有很多人已经完成了你需要做的事情。查看一些现有的JavaScript Loader框架,例如:
There are lots of people who have already done what you need to do. Check out some of the existing JavaScript Loader frameworks, like:
- https://developers.google.com/loader/
http://yepnopejs.com/(deprecated)- http://requirejs.org/
这篇关于使用Javascript加载jQuery并使用jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!