正在等待jquery异步加载,然后再加载js
Waiting for jquery to load asynchronously before loading js
我正在使用以下内容在我的网站上加载广告
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
var adWidth = $(document).width();
google_ad_client = "ca-pub-6777348526535979";
if ( adWidth >= 768 ) {
google_ad_slot = "3870513647";
google_ad_width = 728;
google_ad_height = 90;
} else {
google_ad_slot = "1127560842";
google_ad_width = 320;
google_ad_height = 50;
}
</script>
<script type="text/javascript" src="//pagead2.googlesyndication.com/pagead/show_ads.js"></script>
它运行良好,但我认为我可以进一步优化广告投放。我想异步加载jquery,因此下面的脚本必须等待加载jquery。
<script type="text/javascript">
var adWidth = $(document).width();
google_ad_client = "ca-pub-6777348526535979";
if ( adWidth >= 768 ) {
google_ad_slot = "3870513647";
google_ad_width = 728;
google_ad_height = 90;
} else {
google_ad_slot = "1127560842";
google_ad_width = 320;
google_ad_height = 50;
}
</script>
<script type="text/javascript" src="//pagead2.googlesyndication.com/pagead/show_ads.js"></script>
我怎样才能做到这一点?
您可以这样做:
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
var google_ad_slot;
var google_ad_width;
var google_ad_height;
var google_ad_client;
$(document).ready(function()
{
var adWidth = $(document).width();
google_ad_client = "ca-pub-6777348526535979";
if ( adWidth >= 768 ) {
google_ad_slot = "3870513647";
google_ad_width = 728;
google_ad_height = 90;
} else {
google_ad_slot = "1127560842";
google_ad_width = 320;
google_ad_height = 50;
}
$("head").append('<script type="text/javascript" src="//pagead2.googlesyndication.com/pagead/show_ads.js"></script>');
});
</script>
DOM准备好并加载脚本(包括jQuery)后,jQuery将调用此$(document).ready()
函数,您的值将被启动,Google广告脚本将被添加到文档的head
部分。
所有现代浏览器在将脚本添加到DOM后都能正确加载并运行脚本。
变量应该是全局的,以便Google脚本能够使用它们。如果不起作用,您也可以尝试将$(document).ready
更改为$(window).load
,以确保它已被加载。
我想你要找的是AMD。AMD(异步模块定义)是一种允许Javascript模块显式声明其依赖关系并异步加载的规范。
AMD最著名的实现可能是RequireJS。基本上,您可以从<script>
标签中移动代码,并按如下方式更改它:
require(['jquery'], function($){
var adWidth = $(document).width();
// And the rest of your code
});
不过要注意的是,jQuery并不能很好地支持AMD,所以你必须克服一些困难。RequireJS网站上有处理jQuery的说明。
相关文章:
- AngularJS加载JSON数据,然后从中解析/加载HTML
- 先在Angular中加载配置文件,然后再加载其他文件
- 加载文件,然后调用回调函数
- 如何更改javascript的一个变量,然后运行;“加载”;而无需重新加载页面
- 下拉重新加载页面,然后检索值
- 先加载特定的图像,然后再加载页面的其余部分
- 加载页面,然后在页面加载时执行 javascript
- Angular js,在选择元素上,我想 POST 数据以将其保存在数据库中,然后我想使用 PUT 更新它而无需重新加载
- 使用 jQuery 加载 JSON,然后将其显示给查看器
- 淡出加载然后淡入不起作用
- 可以进行现场重新加载,然后触发点击功能
- 在RadWindow中加载新页面,然后从加载的窗体中关闭窗口
- 加载在JSBN中创建的RSA公钥,然后加密消息
- 加载时可以单击按钮#1,然后需要单击按钮#2两次.按钮#1也需要点击两次
- 地图,rails 4.2,javascript,鼠标悬停,只工作一次(或两次).然后在重新加载之后
- 如何在jQuery中进行页面加载,然后点击
- removeChild,然后再次添加以前删除的Child以重新加载并清理它
- jQuery UI#Accordion加载然后fadeIN..怎样
- 中间的页脚加载然后粘在底部
- 加载然后换行,但是换行在jQuery中不起作用