Making Google Adsense asynchronous seems to be critical to achieving better performance, in this post in the continuing series on optimization of sites (Performance: the effect of Google Adsense and Go Faster Stripes for site performance and Google Adsense), a simple idea has some interesting implications.
<script type="text/javascript"><!--
google_ad_client = "pub-xxxxxxxx";
google_ad_slot = "xxxxxxxx";
google_ad_width = 336;
google_ad_height = 280;
//-->
</script>
<script type="text/javascript"><!--
// dynamically Load Ads out-of-band
setTimeout((function ()
{
// placeholder for ads
var eleAds = document.createElement("ads");
// dynamic script element
var eleScript = document.createElement("script");
// remember the implementation of document.write function
w = document.write;
// override and replace with our version
document.write = (function(params)
{
// replace our placeholder with real ads
eleAds.innerHTML = params;
// put the old implementation back in place
document.write=w;
});
// setup the ads script element
eleScript.setAttribute("type", "text/javascript");
eleScript.setAttribute("src", "http://pagead2.googlesyndication.com/pagead/show_ads.js");
// add the two elements, causing the ads script to run
document.body.appendChild(eleAds);
document.body.appendChild(eleScript);
}), 1);
//-->
</script>
How does this work? Google's Ad script is quite „nasty“ as it uses document.write, generally not a good idea as it can only be used during page creation. So this script does two things:
Now this code is far from bullet proof, or tested (WOMM), but it shows the basic principle - it works only because its specific to the Google code