Dynamic Adsense Insertion With JavaScript

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

Leave a Comment