我使用以下命令将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);
但是,当我运行时:
jQuery(document).ready(function(){...
控制台报告错误:
Uncaught ReferenceError: jQuery is not defined
如何动态加载jQuery并在dom中使用它?
发布于 2017-02-03 06:11:25
您需要在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
}
或者,如果您在异步函数中运行它,则可以在上面的代码中使用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
如果要先检查页面中是否已存在jQuery,请尝试使用this
发布于 2012-04-12 04:28:04
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>
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>
发布于 2012-04-12 04:50:19
出现此错误的原因是JavaScript没有等待脚本加载,所以当您运行
jQuery(document).ready(function(){...
不能保证脚本已经准备好了(而且永远不会准备好)。
这不是最优雅的解决方案,但它是可行的。从本质上说,你可以每隔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);
https://stackoverflow.com/questions/10113366
复制相似问题