How to Use Google AdSense or DFP on a Responsive Website

You, AdSenseDFPjQuery
Back

Responsive web sites are kind of a hot topic these days, every one needs a responsive web site. Most of the today website when the revamp or rebuild they think about making them responsive too.

Unfortunately the advertisements are not. As of today Google AdSense has a responsive ad unit(released July 2013) it's a good solution but it's in a beta yet and you can't trust if it's working or not.

I'm working on a site that needed DFP ads with AdSense backfill. DFP does not support responsive so I came up with the solution below.

Note: This is a Drupal site and code will be more into Drupal standards.

Requirements

Step 1: Include the jQuery DFP to your header section of the website.

Step 2: Create Ad Units for of the sizes 728x90, 468x60, 320x50. Create an order.

Step 3: Create DFP place holder div.

<div class="**dfp-leaderboard**"><div class="**dfp-tag**"\>Your ad will show up here!</div></div>

Step 4: copy and paste the code below in to your script.js file of the site and use refresh_dfp() to create DFP ads.

var refresh_dfp: function () {
   // get size of the window
   var width = $(window).width();
   if (width >= 995) {
     leaderboard_data_dimensions = '728x90';
   } else if ((width < 995) && (width >= 768)) {
     leaderboard_data_dimensions = '728x90';
   } else if ((width < 768) && (width >= 480)) {
     leaderboard_data_dimensions = '468x60';
   } else {
     leaderboard_data_dimensions = '320x50';
   }
   $('.**dfp-leaderboard**').each(function () {
     $('.**dfp-tag**', this).attr('data-dimensions', leaderboard_data_dimensions);
   });
   $.dfp({
     dfpID: **'YOUR DFP ID IS HERE'**
   });
 }
© Heshan Wanigasooriya.RSS

🍪 This site does not track you.