使用 Javascript 加载 jQuery 并使用 jQuery
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10113366/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Load jQuery with Javascript and use jQuery
提问by ThomasReggi
I am appending the jQuery library to the dom using:
我正在使用以下方法将 jQuery 库附加到 dom:
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);
However when I 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?
如何动态加载 jQuery 以及在 dom 中使用它?
回答by Anders Tornblad
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/
这里有一个带有小示例的工作 JSFiddle,它准确地展示了您正在寻找的内容(除非我误解了您的要求):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 的方法存在一些问题。当涉及到非常基础的框架时,例如 jQuery,您实际上可能希望静态加载它们,否则,您将不得不编写一个完整的 JavaScript 加载框架......
You could use some of the existing JavaScript loaders, or write your own by watching for window.jQuery
to get defined.
您可以使用一些现有的 JavaScript 加载器,或者通过 watch forwindow.jQuery
定义来编写自己的加载器。
// 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);
})();
Just remember that if you need to support reallyold 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/
请记住,如果您需要支持非常旧的浏览器,例如 IE8,load
则不会执行事件处理程序。在这种情况下,您需要轮询是否存在window.jQuery
使用重复window.setTimeout
。这里有一个使用该方法的有效 JSFiddle:http: //jsfiddle.net/9N7Z2/3/
There are lots of people who have already done what you need to do. Check out some of the existing JavaScript Loader frameworks, like:
有很多人已经做了你需要做的事情。查看一些现有的 JavaScript Loader 框架,例如:
https://developers.google.com/loader/(no longer documented)http://yepnopejs.com/(deprecated)- http://requirejs.org/
回答by Jacob van Lingen
There is an other way to load jQuery dynamically (source). You could also use
还有另一种动态加载 jQuery 的方法(source)。你也可以使用
document.write('<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"><\/script>');
It's considered bad practice to use document.write
, but for sake of completion it's good to mention it.
使用 被认为是不好的做法document.write
,但为了完成起见,最好提及它。
See Why is document.write considered a "bad practice"?for the reasons. The prois that document.write
does block your page from loading other assests, so there is no need to create a callback function.
请参阅为什么 document.write 被认为是“不好的做法”?原因。该亲是document.write
不加载其他资产产生阻止你的页面,所以没有必要创建一个回调函数。
回答by Code Maverick
<script type="text/javascript"
src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
// You may specify partial version numbers, such as "1" or "1.3",
// with the same result. Doing so will automatically load the
// latest version matching that partial revision pattern
// (e.g. 1.3 would load 1.3.2 today and 1 would load 1.7.2).
google.load("jquery", "1.7.2");
google.setOnLoadCallback(function() {
// Place init code here instead of $(document).ready()
});
</script>
But even he admits that it just doesn't compare to doing the following when it comes to optimal performance:
但即使是他也承认,在最佳性能方面,它无法与执行以下操作相提并论:
<script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js" type="text/javascript"></script>
<script type="text/javascript"> window.jQuery || document.write('<script src="js/libs/jquery-1.7.2.min.js">\x3C/script>')</script>
<script type="text/javascript" src="scripts.js"></scripts>
</body>
</html>
回答by aljgom
You need to run your code AFTER jQuery finished loading
您需要在 jQuery 完成加载后运行您的代码
var script = document.createElement('script');
document.head.appendChild(script);
script.type = 'text/javascript';
script.src = "//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js";
script.onload = function(){
// your jQuery code here
}
or if you're running it in an async function you could use await
in the above code
或者如果你在异步函数中运行它,你可以await
在上面的代码中使用
var script = document.createElement('script');
document.head.appendChild(script);
script.type = 'text/javascript';
script.src = "//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js";
await script.onload
// your jQuery code here
If you want to check first if jQuery already exists in the page, try this
如果你想先检查页面中是否已经存在 jQuery,试试这个
回答by kenorb
From the DevToolsconsole, you can run:
从DevTools控制台,您可以运行:
document.getElementsByTagName("head")[0].innerHTML += '<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"><\/script>';
Check the available jQuery version at https://code.jquery.com/jquery/.
在https://code.jquery.com/jquery/检查可用的 jQuery 版本。
To check whether it's loaded, see: Checking if jquery is loaded using Javascript.
要检查它是否已加载,请参阅:Checking if jquery is loaded using Javascript。
回答by coder
HTML:
HTML:
<html>
<head>
</head>
<body>
<div id='status'>jQuery is not loaded yet.</div>
<input type='button' value='Click here to load it.' onclick='load()' />
</body>
</html>
Script:
脚本:
<script>
load = function() {
load.getScript("jquery-1.7.2.js");
load.tryReady(0); // We will write this function later. It's responsible for waiting until jQuery loads before using it.
}
// dynamically load any javascript file.
load.getScript = function(filename) {
var script = document.createElement('script')
script.setAttribute("type","text/javascript")
script.setAttribute("src", filename)
if (typeof script!="undefined")
document.getElementsByTagName("head")[0].appendChild(script)
}
</script>
回答by marteljn
The reason you are getting this error is that JavaScript is not waiting for the script to be loaded, so when you run
您收到此错误的原因是 JavaScript 没有等待脚本加载,因此当您运行时
jQuery(document).ready(function(){...
there is not guarantee that the script is ready (and never will be).
不能保证脚本已准备好(并且永远不会)。
This is not the most elegant solution but its workable. Essentially you can check every 1 second for the jQuery object ad run a function when its loaded with your code in it. I would add a timeout (say clearTimeout after its been run 20 times) as well to stop the check from occurring indefinitely.
这不是最优雅的解决方案,但它是可行的。本质上,您可以每 1 秒检查一次 jQuery 对象广告是否在加载了您的代码时运行了一个函数。我还会添加一个超时(比如在运行 20 次后 clearTimeout)以阻止检查无限期发生。
var jQueryIsReady = function(){
//Your JQuery code here
}
var checkJquery = function(){
if(typeof jQuery === "undefined"){
return false;
}else{
clearTimeout(interval);
jQueryIsReady();
}
}
var interval = setInterval(checkJquery,1000);
回答by txominpelu
Using require.jsyou can do the same thing in a safer way. You can just define your dependency on jquery and then execute the code you want using the dependency when it is loaded without polluting the namespace:
使用require.js您可以以更安全的方式做同样的事情。您可以定义对 jquery 的依赖,然后在加载时使用该依赖执行您想要的代码,而不会污染命名空间:
I generally recommend this library for managing all dependencies on Javascript. It's simple and allows for an efficient optimization of resource loading. However there's some precautionsyou may need to take when using it with JQuery . My favourite way to deal with them is explained in this github repoand reflected by the following code sample:
我通常推荐这个库来管理对 Javascript 的所有依赖。它很简单,可以有效优化资源加载。但是,在将它与 JQuery 一起使用时,您可能需要采取一些预防措施。我最喜欢的处理它们的方式在这个github repo 中进行了解释,并反映在以下代码示例中:
<title>jQuery+RequireJS Sample Page</title>
<script src="scripts/require.js"></script>
<script>
require({
baseUrl: 'scripts',
paths: {
jquery: 'https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min'
},
priority: ['jquery']
}, ['main']);
</script>