Responsive Google AdSense Ads

joe.price's picture

In Drupal, the AdSense module provides a way to easily implement Google AdSense Managed Ads on your site. The problem is, the ad size is fixed in the module generated blocks. For a responsive site, this can be a real problem -- a 728x90 Leaderboard ad isn't going to display properly on a 320px smartphone. After testing a few other alternatives, a really flexible solution is a custom block.

In essence, the code checks at page load to see:

  1. If the screen width is >= 768px, then load the Leaderboard ad size.
  2. If its between 767px and 468px, then load the Banner ad size.
  3. If its between 467px and 336px, the load the Mobile Banner ad size.
  4. If its smaller than 335px, don't load any ad.

Easy enough right? Be sure to replace google_ad_client = "ca-pub-xxxx" and google_ad_slot = "AAA" with your correct information.

UPDATE -- Google has made this even easier with a single Responsive ad unit (BETA)

Any of the ad sizes and screen dimensions can be customized to your needs. You can have two alternative ads and sizes, or ten.

Tags: