Dynamic Adsense Insertion With JavaScript

百般思念 提交于 2019-11-27 06:59:02
Johnny Oshika

The simple technique used to asynchronously load the AdSense script proposed by other answers won't work because Google uses document.write() inside of the AdSense script. document.write() only works during page creation, and by the time the asynchronously loaded script executes, page creation will have already completed.

To make this work, you'll need to overwrite document.write() so when the AdSense script calls it, you can manipulate the DOM yourself. Here's an example:

<script>
window.google_ad_client = "123456789";
window.google_ad_slot = "123456789";
window.google_ad_width = 200;
window.google_ad_height = 200;

// container is where you want the ad to be inserted
var container = document.getElementById('ad_container');
var w = document.write;
document.write = function (content) {
    container.innerHTML = content;
    document.write = w;
};

var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://pagead2.googlesyndication.com/pagead/show_ads.js';
document.body.appendChild(script);
</script>

The example first caches the native document.write() function in a local variable. Then it overwrites document.write() and inside of it, it uses innerHTML to inject the HTML content that Google will send to document.write(). Once that's done, it restores the native document.write() function.

This technique was borrowed from here: http://blog.figmentengine.com/2011/08/google-ads-async-asynchronous.html

I already have adsense on my page but also inject new ads into placeholders in my blog article. Where I want an advert injecting I add a div with a class of 'adsense-inject' then I run this script when the doc is ready and I know the adsense script has already been loaded for the other adverts:-

    $(document).ready(function()
    {
        $(".adsense-inject").each(function () {
            $(this).append('<ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-3978524526870979" data-ad-slot="6927511035" data-ad-format="auto"></ins>');
            (adsbygoogle = window.adsbygoogle || []).push({});
        }); 
    });

Here is an updated implementation, this is useful if you need no manage the Ads using a common external javascript include, in my case I have a lot of static html files and it works well. It also offers a single point of management for my AdSense scripts.

var externalScript   = document.createElement("script");
externalScript.type  = "text/javascript";
externalScript.setAttribute('async','async');
externalScript.src = "//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js";
document.getElementsByTagName('body')[0].appendChild(externalScript);

var ins   = document.createElement("ins");
ins.setAttribute('class','adsbygoogle');
ins.setAttribute('style','display:block;');/*add other styles if required*/
ins.setAttribute('data-ad-client','ca-pub-YOUR-CLIENTID');
ins.setAttribute('data-ad-slot','YOUR-SLOTID');
ins.setAttribute('data-ad-format','auto');
document.getElementsByTagName('body')[0].appendChild(ins);

var inlineScript   = document.createElement("script");
inlineScript.type  = "text/javascript";
inlineScript.text  = '(adsbygoogle = window.adsbygoogle || []).push({});'  
document.getElementsByTagName('body')[0].appendChild(inlineScript); 

Example of usage:

<script type="text/javascript" src="/adinclude.js"></script>

What about having the vars (google_ad_client, etc) always in the head and dynamically append the other part like this:

var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://pagead2.googlesyndication.com/pagead/show_ads.js';
myDIV.appendChild(script); 

According to this page, it is possible to generate script tags and populate their src fields on the fly - which is what @noiv suggests (my version here should be self-contained; no external html or js libraries required). Have you tried this out? It does not seem so difficult...

function justAddAdds(target_id, client, slot, width, height) {
  // ugly global vars :-P
  google_ad_client = client;
  google_ad_slot = slot;
  google_ad_width = width;
  google_ad_height = height;
  // inject script, bypassing same-source
  var target = document.getElementById(target_id);
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = 'http://pagead2.googlesyndication.com/pagead/show_ads.js';
  target.appendChild(script);
}

These methods will work but they will not work for https. If you want to place ads dynamically and use https you will need to sign up for Double Click For Publishers.

I had this problem on my site so I put together an npm module to solve this problem for myself. Hope you find it useful.

Use Adsense in Single Page Web Apps

The link contains full sample code of how to use the module in a single page web app.

Once you have the module installed this code will display your ad in the element you specify: ViceView.showAdsense({adslot: {slot: "myslot", sizes: "[300,100]", id:"your adsenseid"}, element: "element", adwidth: 300, adheight: 100});

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!