Monday, December 31, 2012

How to use Google AdSense Ads on Responsive Websites

Responsive web design is a simple yet powerful technique that makes your website look good across all screen sizes be it mobile phones, tablets, desktop or even the TV.
Google also recommends the responsive design approach for improved indexing since “it keeps your desktop and mobile content on a single URL.”

Responsive Google Ads

If you been using Google AdSense Ads on your responsive website, you may have noticed that, unlike your content, the Google ads have a fixed width and they will not shrink or expand based on the device size.
For instance, if you are using the standard 728×90 unit on your website, the ad unit may extend well beyond the screen if someone visits your website on a (320 pixels wide) mobile phone or one of the lower resolution tablets.
Google AdSense Ads aren’t responsive by default but you can use a bit of JavaScript code to make them respond to the screen size. The logic is pretty simple. You create multiple ad units (say 768×90, 468×60 and 300×250) and based on the size (width) of the user’s device, the most appropriate format get  served.
Here’s the relevant JavaScript code:
<script type="text/javascript">
    google_ad_client = "ca-publisher-id";
    if (window.innerWidth >= 800) {
        google_ad_slot = "ad-unit-1";
        google_ad_width = 728;
        google_ad_height = 60;
    } else if (window.innerWidth < 400) {
        google_ad_slot = "ad-unit-2";
        google_ad_width = 300;
        google_ad_height = 250;
    } else {
        google_ad_slot = "ad-unit-3";
        google_ad_width = 468;
        google_ad_height = 60;
    }
</script>
<script type="text/javascript" 
 src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
Remember to replace the google_ad_client and google_ad_slot identifiers with your own values (you can easily find them in your AdSense JavaScript code).
Internally, it is the window.innerWidth property that is doing all the magic. This property contains the width (in pixels) of the user’s browser window and once you know that value, you can accordingly serve the larger or smaller AdSense ad units.
While it is always a good idea to confirm with your account manager, this shouldn’t be against AdSense TOS in my opinion since we aren’t resizing the ads or modifying the JavaScript code – we are just serving a different ad unit based on the visitor’s browser size.
AdSense publishers routinely perform split A/B testing to determine which colors schemes and banners sizes perform the best on their website – this is a similar technique.

No comments: