Jef*_*eff 34 javascript jquery dynamic
我有一个包含以下内容的initializor.js:
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);
}
Run Code Online (Sandbox Code Playgroud)
然后我将该文件包含在另一页的某个地方.代码检查是否加载了jQuery,如果不加载,则将其添加到Head标记.
但是,jQuery没有初始化,因为在我的主文档中,我声明了一些事件来测试它.我还尝试在支票下面编写一些jQuery代码,Firebug说"jQuery未定义".这是一种方法吗?Firebug在head标签中显示jquery包含标签!
另外,我可以动态地将代码添加到$(document).ready()事件中吗?或者只是将一些Click事件添加到几个元素中?
Ada*_*ath 48
当您异步加载它时(通过将其附加到<head>
),jQuery不会立即可用.您必须向脚本(jqTag
)添加一个onload侦听器,以检测它何时加载然后运行您的代码.
例如
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();
}
Run Code Online (Sandbox Code Playgroud)
bea*_*ode 29
要包含jQuery,您应该使用:
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="jquery.js">\x3C/script>')</script>
Run Code Online (Sandbox Code Playgroud)
它使用谷歌CDN,但提供后备和协议相对URL.
注意:请务必将版本号更改为最新版本
如果window.jQuery
已定义,它将不会继续读取该行,因为它是一个或已经包含一个真值,如果不是它wil(document.)写入值,
请参阅:theHTML5Boilerplate
还有:你忘记了引号,如果没有定义jQuery:
typeof window.jQuery === "undefined" //true
typeof window.jQuery == undefined //false ,this is wrong
Run Code Online (Sandbox Code Playgroud)
你还可以:
window.jQuery === undefined //true
Run Code Online (Sandbox Code Playgroud)
alj*_*gom 10
重构Adam Heath的答案(这是更可读的IMO).最重要的是,你需要在jQuery完成加载后运行jQuery代码.
jQueryCode = function(){
// your jQuery code
}
if(window.jQuery) jQueryCode();
else{
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 = jQueryCode;
}
Run Code Online (Sandbox Code Playgroud)
如果您使用的是异步功能,则可以使用await
,就像这样
function runWithJQuery(jQueryCode){
if(window.jQuery) jQueryCode();
else{
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 = jQueryCode;
}
}
runWithJQuery(function jQueryCode(){
// your jQuery code
})
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
50991 次 |
最近记录: |