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

<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 Ad脚本添加到文档的head部分。

将所有脚本添加到DOM后,所有现代浏览器均可正确加载并运行脚本。

变量应该是全局变量,以便Google脚本可以使用它们。
如果无法完全确定已将其加载,也可以尝试将$(document).ready更改为$(window).load

10-07 14:11
查看更多