无法动态地将 jquery 添加到头部并运行 jquery 代码
Cant add jquery to the head dynamically and run jquery code
我有这个代码:
function init(){
if (typeof window.jQuery !== 'function') {
var link = document.createElement('script');
link.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js';
document.getElementsByTagName('head')[0].appendChild(link);
}
}
window.onload = init;
if (typeof window.jQuery === 'function') {
$(document).ready(function(){
alert(1);
});
}
我正在尝试做的是在 jQuery 不存在的情况下将 jquery 脚本链接添加到头部,然后运行代码。最好的办法是尽快检查 jquery 是否存在于头部,然后添加指向源代码的链接。但我不知道如何实现?
更新:另一种方法是使用函数:
function init(){
if (typeof window.jQuery !== 'function') {
var link = document.createElement('script');
link.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js';
document.getElementsByTagName('head')[0].appendChild(link);
start_code();
}
else{
start_code();
}
}
window.onload = init;
function start_code(){
$(document).ready(function(){
alert(1);
});
}
我基本上可以在加载所有内容后调用一个函数。但这并不奏效。因为 $ 未定义错误也被抛出
function init(){
if (typeof window.jQuery !== 'function') {
var link = document.createElement('script');
link.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js';
document.getElementsByTagName('head')[0].appendChild(link);
}
}
或使用HTML5 boilerplate
方法
<script>window.jQuery || document.write('<script src="/js/vendor/jquery-1.7.2.min.js"><'/script>')</script>
将此脚本放在页面底部(出于性能目的)。那么,如果你之前需要使用jQuery函数,看看这个资源就知道了:停止支付你的jQuery税
由于document.write
这里正在创建一个脚本块(这是同步的),您所要做的就是
<script>window.jQuery || document.write('<script src="/js/vendor/jquery-1.7.2.min.js"><'/script>')</script>
<script>
$(document).ready(function(){
alert(1);
});
</script>
相关文章:
- 在<头部>使用javascript/jQuery
- "$"未定义;jquery在<头部>;没有冲突的脚本或库
- 无法动态地将 jquery 添加到头部并运行 jquery 代码
- 如何获取头部中提到的jquery文件的链接
- Jquery 删除输出上的头部和身体标签
- 头部部分的 JQuery 不起作用
- 为什么 jQuery 在使用样式标签填充 iframe 时会删除正文和头部标签,但不能没有样式标签
- jQuery在底部,等待<头部>直到它被加载
- jQuery移动可折叠按钮在头部,停止折叠/展开
- 使用移动版jquery和cordova时,可折叠列表视图的头部不能刷新
- JQuery头部格式语法(CSS)
- 如何使用JS/AJAX/JQUERY为POST表单添加头部授权
- 在PHP页面中加载jQuery -没有头部标签
- 我如何添加jQuery头部与JavaScript
- 为什么用jQuery在头部插入脚本如此奇怪?
- jQuery通过JS加载在头部
- 我如何检索数据行,取决于头部选择的值使用jquery
- 结合jQuery表和头部:如何分配最终的html输出
- Js /jquery替换头部注释中的内容
- 注入css链接到头部与javascript/jquery