如果没有加载jQuery,我该如何加载? [英] How can I load jQuery if it is not already loaded?
问题描述
我有一个 initializor.js ,其中包含以下内容:
I have a initializor.js that contains the following:
if(typeof jQuery=='undefined')
{
var headTag = document.getElementsByTagName("head")[0];
var jqTag = document.createElement('script');
jqTag.type = 'text/javascript';
jqTag.src = 'jquery.js';
headTag.appendChild(jqTag);
}
然后,我将该文件包含在另一页面上的某个位置。代码检查jQuery是否加载,如果它不是,将它添加到Head标签。
I am then including that file somewhere on another page. The code checks if jQuery is loaded, and if it isnt, add it to the Head tag.
但是,jQuery没有初始化,因为在我的主要文档中,我有一些事件宣称只是为了测试这个。我也尝试在支票下方写一些jQuery代码,Firebug表示jQuery是未定义的。是这样做吗? Firebug在head标签中显示jquery包含标签!
However, jQuery is not initializing, because in my main document, I have a few events declared just to test this. I also tried writing some jQuery code below the check, and Firebug said "jQuery is undefined". Is tbere a way to do this? Firebug shows the jquery inclusion tag within the head tag!
此外,我可以动态地将代码添加到$(document).ready()事件中吗?或者不是只需要添加一些Click事件到一些元素?
Also, can I dynamically add code into the $(document).ready() event? Or wouldnt it be necessary just to add some Click events to a few elements?
推荐答案
jQuery在您正在加载时不可立即它异步(通过将其附加到< head>
)。您必须向脚本( jqTag
)添加一个负载监听器,以检测何时加载,然后运行代码。
jQuery is not available immediately as you are loading it asynchronously (by appending it to the <head>
). You would have to add an onload listener to the script (jqTag
) to detect when it loads and then run your code.
例如
function myJQueryCode() {
//Do stuff with jQuery
}
if(typeof jQuery=='undefined') {
var headTag = document.getElementsByTagName("head")[0];
var jqTag = document.createElement('script');
jqTag.type = 'text/javascript';
jqTag.src = 'jquery.js';
jqTag.onload = myJQueryCode;
headTag.appendChild(jqTag);
} else {
myJQueryCode();
}
这篇关于如果没有加载jQuery,我该如何加载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!