正在等待jquery异步加载,然后再加载js

Waiting for jquery to load asynchronously before loading js

本文关键字:加载 然后 js jquery 异步 在等待      更新时间:2023-09-26

我正在使用以下内容在我的网站上加载广告

<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的说明。