How to Use Google DFP and Adsense on a Responsive Website


This article shows how to mix Adsense and direct campaigns using Google DFP and get it all working on a responsive website.

Google also offer Adsense Direct which allows the publisher to negotiate an ad deal that will be served through adsense.

The Challenge

There is no one-size-fits-all solution for a responsive website.

RWD continues to evolve with an increasing number of design patterns. In the advertising world things are also continuously changing.

Every site is unique and it is that particular site’s design, content, and UX that will govern how media breakpoints are set and where ad units are displayed – not any cookie-cutter approach.

Mobile web usage is growing rapidly – our site went from 12% mobile traffic to 44% mobile in exactly 2 years. That’s 430% growth.

The main goals are this:

  • Allow some ad slots to serve different sized creative depending on the viewport size.
  • Allow some ad slots to be hidden on different viewports (e.g. a wide layout might have 3 adslots, in mobile only a single ad).

Solution 1: Using CSS and jQuery to choose different DFP Ad Units

This is what we are doing at the moment (props to levo).

Twitter Bootstrap has some handy CSS classes that allow you to show and hide DIV blocks depending on the viewport size. The CSS below is for desktop size (this is from Bootstrap 2 – a little outdated).

.visible-phone { display: none !important; }
.visible-tablet { display: none !important; }
.hidden-phone { }
.hidden-tablet { }
.hidden-desktop { display: none !important; }
.visible-desktop { display: inherit !important; }

Our mobile media query looks like this:

@media screen and (max-width: 650px) {
	.hidden-desktop { display: inherit !important; }
	.visible-desktop { display: none !important; }
	.visible-phone { display: inherit !important; }
	.hidden-phone { display: none !important; }

This allows us to set any DIV to show or hide depending on the viewport size.

<div class="hidden-phone">
	This information will only appear on desktop layouts.

Adding the DFP Ad Units

Let’s say we have a sidebar that should show a 300×250 ad to desktop, and a 250×250 to tablet. We set up two DIVs like this:

<div class="adslot visible-desktop" id="div-gpt-ad-1325545340561-0" style="width: 300px; height: 250px;" data-dfp="Adunit_300x250" data-cids="7956726685"></div> 
<div class="adslot visible-tablet" id="div-gpt-ad-1325545340561-1" style="width: 250px; height: 250px;" data-dfp="Adunit_250x250" data-cids="5374604278"></div>

Then in our Javascript we do the following (you must use the Google Publisher Tag – GPT, and be using jQuery).

Firstly the GPT call.

<script type="text/javascript">// <
var googletag = googletag || {};
googletag.cmd = googletag.cmd || [];
(function() {
	var gads = document.createElement('script');
	gads.async = true;
	gads.type = 'text/javascript';
	gads.src = '';
	var node = document.getElementsByTagName('script')[0];
	node.parentNode.insertBefore(gads, node);


Then after this:

	var dfpslots=$("#wrapper").find(".adslot").filter(":visible"),
	slot= new Array();

	if (dfpslots.length) {
		googletag.cmd.push(function() {
				slot[i] = googletag.defineSlot('/9999999/'+$(this).attr('data-dfp'), [$(this).width(), $(this).height()], 	$(this).attr('id')).addService(googletag.pubads());
				if ($(this).attr('data-cids')) slot[i].set("adsense_channel_ids", $(this).attr('data-cids'));

			//googletag.pubads().enableSingleRequest(); // Breaks channel reporting


This code iterates through all visible ad slot DIVs, then creates DFP Ad Slots for each one (replace 9999999 with your dfp id), incorporates AdSense channels with the data-cids attribute.

After setting up each slot, the display method is called for each one.

To check your DFP implementation append ?google_console to your page’s URL and refresh. Then hit Fn-Ctrl-F10 (or Ctrl-F10 on Windows).

Ad Units with Multiple Sizes

If you have an ad unit where you want to serve more than one size (for example a 300×250 and a 300×600) you will need to alter the code.

Firstly the ad call (this might be in a sidebar):

<div id="div-gpt-ad-1325545340561-0" class="visible-desktop" data-sizes='[[300,250],[300,600]]' data-dfp="Adunit_Sidebar" data-cids="7956726685"></div> 

Remove the hard-coded width and height.
Add in a new attribute called data-sizes, and include an array of different ad sizes.

Now on the setup code:

			 if ($(this).attr('data-sizes')) {
				 var sizes = $(this).data('sizes');
				 for (var i=0; i < sizes.length; i++){
			 } else {
				 var sizes = [$(this).width(), $(this).height()];

			 slot[i] = googletag.defineSlot('/1084798/'+$(this).attr('data-dfp'), sizes, $(this).attr('id')).addService(googletag.pubads());
				if ($(this).attr('data-cids')) slot[i].set("adsense_channel_ids", $(this).attr('data-cids'));

We’ve added some new code to test if the data-sizes attribute exists. If it does, then extract out the sizes. If not, then look for the normal hard-coded width and height.

Then in defining the adslot we put in our sizes array. This will then pass the multiple sizes for DFP to do with as it pleases. Make sure your DFP ad unit is set to the multiple sizes also.

Solution 2: Showing / Hiding Ad Slots Without CSS

In the above solution we used the CSS styles (hidden-phone etc) to show or hide the relevant ad slots. This could be done in JavaScript instead.

<script type="text/javascript">// <![CDATA[
googletag.cmd.push(function() {
googletag.defineSlot('/9999999/myadunit_300x250', [300, 250], 'div-gpt-ad-3248237498728-1').addService(googletag.pubads());
googletag.defineSlot('/9999999/myadunit_728x90', [728, 90], 'div-gpt-ad-3248237498728-2').addService(googletag.pubads());

var width = window.innerWidth || document.documentElement.clientWidth;

if (width >= 768) {
	googletag.defineSlot('/9999999/myadunit_bottom_728x90', [728, 90], 'div-gpt-ad-3248237498728-2').addService(googletag.pubads());
else if ((width >= 300) && (width < 768)) {
	googletag.defineSlot('/9999999/myadunit_mobile_only', [300, 250], 'div-gpt-ad-3248237498728-1').addService(googletag.pubads());
// ]]></script>

With this approach the setting of the appropriate ad slots happens on page load only. Tablets and Desktops get a leaderboard, and Smartphones get a 300×250 instead of this.

Solution 3: DFP Responsive Ad Units

Google DFP have rolled out responsive mappings. Here you can set a series of preferred ad sizes based on browser size.

It’s a little complex, but once it is all working, it’s a good way of offering multiple creative sizes to a single ad slot based on viewport size.

  1. Include the GPT script
  2. Create a mapping for each creative size

Example – Leaderboard ad for all Screen Sizes

googletag.cmd.push(function() {
	var mapLeader = googletag.sizeMapping().
		addSize([320, 400], [320, 50]).
		addSize([320, 700], [300, 75]).
		addSize([480, 200], [468, 60]).
		addSize([768, 200], [728, 90]).
		addSize([1000, 200], [970,90]).
	window.LeaderSlot= googletag.defineSlot('/1084798/Test_Multi_Width', [320,50], 'div-gpt-ad-1393979881710-0').



Further on our ad slot declaration is standard DFP:

<div id="div-gpt-ad-1393979881710-0" class="wide-ad"><script type="text/javascript">// <![CDATA[
googletag.cmd.push(function() {googletag.display('div-gpt-ad-1393979881710-0'); });
// ]]></script></div>

Here’s how it works

  • Each addSize command matches a viewport size [width,height] followed by a creative size [width,height]
  • The viewport size works like min-width in CSS media queries.
  • Example addSize([320, 400], [320, 50]). – where the viewport width is >= (greater than or equal to) 320 pixels serve an ad with creative size of 320×50 (mobile leaderboard).
  • Our example will serve all primary leaderboard sizes for all different size viewports. Typically these would match your CSS media breakpoints.
  • There is one extra bit here: We will serve a 300×75 where the viewport is 320px wide AND the viewport height is >= 700px (e.g. a tall smartphone).

We would assign one (or many line items) to the ad unit, ensuring we have creatives set-up for everything we have listed in our mapping. If you have AdSense setup as backfill, AdSense plays nicely and will also serve the matching creatives that we have specified.

This is a powerful solution as we setup a single ad slot on our page, and serve multiple different sized ads to AND allow them to compete with AdSense backfill that also serves responsively sized creative.

In my testing I’ve noticed that using collapseEmptyDivs() seems to prevent the mappings from working properly.

You’ll notice I’ve set the Ad Unit size to [0,0] on the display call. I found that if the viewport was ever less than our mapping (e.g. less than 320px, DFP would display the creative size listed on display call – so by setting it to size 0 – nothing is displayed).

Refreshing Ads
It is possible to code for viewport resize – something like this works:

This adds an event listener for the resize event, and only fires it after 250ms (otherwise we have continuous refreshes).

We then pass the adslot variable to the DFP refresh method to redo the ad calls for that ad slot.

Go check out my working example here – it uses the code above.

Targeting DFP Ads

It is possible to have line items show up only on certain pages on your site.

Google Anchor Ads

Google now have a new ad unit called an Anchor Ad.

This is for mobile devices and the ad will stay fixed at the bottom of the user’s screen, even as the user scrolls up or down.

I have tested these, they work well although they are disruptive if you have forms on your page. It also seems they don’t seem to pay as well as normal ads of the same size.

I’m not convinced yet.

Other Solutions

There is an interesting script called LazyAds that allows you to wrap the ad calls in comments, and will only execute the tags if matching a media query.

UPDATE: Sep 13 – New Anchor Ads.
UPDATE: Oct 13 – New DFP responsive code.
UPDATE: Mar 14 – Complete overhaul.
UPDATE: Nov 14 – How to target URLs

James Foster
James makes websites, you can follow him on @exisweb.
Filed under Responsive Design
Updated: December 19, 2014


  1. Great article. I’ve been working on a responive design all weekend and this was one of only two posts I found that addressed DFP.

    How do I debug it? It worked once for me but looking at the generated source, most times it’s not inserting anything into my div.


    • Use the Google Console: link. Basically you append ?google_console=1 to the URL, and then Fn-Ctrl-F10. It brings up a window where you can fully debug what’s happening with your ad calls.

      Just remember that depending on your ad fill rate, sometimes you can get blank ads when repeatedly testing on your local server.

      • Hi James,

        Just to clarify, it’s not that an ad is not showing up, but that when I look at the generated source in FF, the ad serving JavaScript is not being being inserted into the div. At one point, just to make sure it was detecting the visible div, I put an ‘alert(“Visible div”)’ after the ‘if (dfpslots.length) {‘ line and it was detecting the visible div. It just wasn’t taking the next step and creating the Google DFP tag. Curious.

        • Also, the data-dfp attribute in your ad divs MUST match the names of your ad units in DFP.

    • Ian, you could add some more debugging throughout the code by using

      Console.log(“my message here”);

      Then using either Firebug, or the FF Developer Toolbar you can see your messages. Also make sure you’ve got your dfp id correct. What did the Google Publisher debug window show you? It’s quite helpful.

      If you know that you’ve got this Javascript correct, and that its making the ad call, then it’s a DFP problem. DFP can be a pig to setup correctly.

      Feel free to paste your code here.

  2. Egads…didn’t realize my old template was already declaring ad slots. when I cleared that up it started working. The console definitely helped notice my mistake!

  3. A great share. Rather unusual approach to dynamic ad unit. In general, what do you recommend the use of ad units. thanks

    • Hey Bora, I’m not quite understanding your question. With DFP Small Business things start to get confusing as you get ad units in DFP and ad units in Adsense. The ad units in adsense effectively become redundant as you are no longer using adsense code, but I using the DFP backfill options. That’s why setting channels properly becomes so important for reporting.

  4. firstly, thanks for the response. I’m not advertising. I wanted to ask about this, as an independent, ad sizes and placement for a blog which gives the best results. Can be a difficult question to, expect an answer based on experience.

    • The only thing you can do is to test different layouts and find out which works best. We’ve been running 300x250s in the sidebar for years and noticing that ad blindness is really setting in, and they are not working so well anymore.

      728×90 across the top are common, but Adsense reps recommend that they sit below the nav bar for better performance.

      We have found some success on a mobile layout by placing a 300×250 below the blog content (before the comments).

  5. Having one of those coding days where something is obvious but I’m just not seeing it. So additional eyeballs are much appreciated! :-)

    Using the Bootstrap queries I have the following in my .css:

    /* For desktops */
    .visible-phone { display: none !important; }
    .visible-tablet { display: none !important; }
    .hidden-phone { }
    .hidden-tablet { }
    .hidden-desktop { display: none !important; }
    .visible-desktop { display: inherit !important; }

    /* Tablets & small desktops only */
    @media (min-width: 768px) and (max-width: 979px) {
    .hidden-desktop { display: inherit !important; }
    .visible-desktop { display: none !important ; }
    .visible-tablet { display: inherit !important; }
    .hidden-tablet { display: none !important; }
    /* Phones only */
    @media (max-width: 767px) {
    .hidden-desktop { display: inherit !important; }
    .visible-desktop { display: none !important; }
    .visible-phone { display: inherit !important; }
    .hidden-phone { display: none !important; }

    At below 767px, I’m getting both the visible-phone and visible-tablet adslots displaying when it should just be the phone. My adslots:

    I tried adding some visible/hidden tablet rules to the smallest media query but only succeeded in having the leaderboard show up as well. [reaches for coffee!] So I obviously screwed up the rules I added. Removed them and back to the original problem. What do I need to add to the max-width: 767px query to make sure that the visible-tablet and hidden-tablet rules in that query do the right thing?


    • Okay. I’m confused. These rules are exactly what I have on two sites and they work fine. What are you using to test your responsive design. I find the responsive design tool in FF is quite good (Tools/WEb DEveloper/ Responsive Design View). And of course having access to actual devices is the best thing.

      Your rules look fine so something else is at play.

      • Finally ended up removing JQuery plugins one by one and it turns out it was an old matchmedia polyfill that was causing the issue. Now that’s gone your wonderful example is working just fine. No more late night coding! :-)

        • Sweet. Glad you got it going.

  6. it doesn’t seem to work with the standard bootstrap media queries. on resize the unwanted ads disappear, but the ones i want to be displayed don’t show up. i assume i also need to use the custom css you provided?

    • leo this won’t work on browser resize. One reason is that if you did put in a bunch of extra javascript to retrieve a new ad, again you would be breaking AdSense T&C’s. There should only be one ad impression per page view. If you resize THEN refresh the page, everything should be working as expected.

      I researched this a bit and people resizing the browser is very rare. One thing that is a concern is an orientation change on a tablet where you go from (in the case of iPad) 768px wide top 1024px wide. It all depends on your layout.

    • Hi Levo, nice to see your comment. Yeah I was the person responding on the WMW thread (synthese). So I’ve taken your stellar work and tweaked it a bit, and also shown other options that Google allow you to do.

      Would love to see any more suggestions from you regarding better implementations of this (and I’ve also added a link back to you WMW thread).

    • Thanks I updated the post. It’s a start but I expect to hear more from them later on in the year.

  7. If you don’t want to track adsence channels, is it just a case of removing “if ($(this).attr(‘data-cids’)) slot[i].set(“adsense_channel_ids”, $(this).attr(‘data-cids’));”?

    • Yes, remove that line. Although if you don’t have the attribute “data-cids” on your div, it won’t execute this line of code anyway.

      • Perfect Thanks!

  8. Hey, thanks for the info on making Google Adsense responsive. I recently struggled with this issue and trying to swap out ads just broke my layout.

    However, I was able write a little jQuery plugin called Rad.js that resizes them. It uses CSS3 scaling and jQuery wrapper resizing to imitate normal responsiveness. Check it out if the current solutions to responsive ads don’t work for you.

    • Nice Work Matt!

      A couple of questions: Not sure if scaling ads are allowed as part of Adsense t&c’s, and also does it work for flash ads?? Not that Google serve a flash ad to a mobile device.

  9. have try to implement your solutions, but ads not shown at all. I can see that div – have correct, but no ads there. Can you help on this?

    • It’s difficult to diagnose blank ads with DFP. Have you tried using their debug tool? See more here

      This will at least tell you whether the correct ad units are being called. If everything looks fine in here and you are still getting blanks, it could be that Adsense is not filling the slot (I frequently see this when testing on a local server).

  10. Hi James,

    I love this idea and have managed to get all of our ad spots except one loading via jQuery.

    Is it possible to hard code another ad unit in to the invocation code?

    I’d like to add the following but cannot see where else it would go apart from after the line that generates the slot array. This is the line i’d like to add…

    googletag.defineSlot(‘/4856165/BackgroundWallpaper’, [1, 1], ‘background-wallpaper’).addService(googletag.pubads());

    And this is what I’ve tried but to no avail :-(

    jQuery(window).load(function() {
    var dfpslots=jQuery(“#wrapper”).find(“.adslot”).filter(“:visible”),
    slot= new Array();
    if (dfpslots.length) {
    googletag.cmd.push(function() {
    slot[i] = googletag.defineSlot(‘/4856165/’+jQuery(this).attr(‘data-dfp’), [jQuery(this).width(), jQuery(this).height()], jQuery(this).attr(‘id’)).addService(googletag.pubads());
    if (jQuery(this).attr(‘data-cids’)) slot[i].set(“adsense_channel_ids”, jQuery(this).attr(‘data-cids’));
    googletag.defineSlot(‘/4856165/BackgroundWallpaper’, [1, 1], ‘background-wallpaper’).addService(googletag.pubads());
    googletag.pubads().setTargeting(‘SiteType’, ‘website’);
    googletag.pubads().setTargeting(‘AreaType’, );



    • James, you would need to make it:

      slot[i] = googletag.defineSlot(‘/4856165/BackgroundWallpaper’, [1, 1], ‘background-wallpaper’).addService(googletag.pubads());

      In this way you add your manual ad unit into the slot array. It would then get called in the dfpslots loop further down.

      What’s with the width and height of 1? Is it some kind of big ad unit?

      • Hi James, thanks for your help. Yes it’s a third party DFP creative containing jQuery that I’ve setup – it wraps our main website wrapper in a two column wallpaper ad and it needs to be a 1×1 interstitial to work.

      • Hi James,

        I’ve tried adding that line but I’m still getting the following error…

        googletag.defineSlot was called without a matching googletag.display call.

        I’ve added the following line to our template as needed…

        but for some reason it’s not working. I’d really love to get this sorted as it’s working a treat on all the other ad slots.


        • Scratch that last comment, the div I was trying to target was outside of the #wrapper target. I’ve amended the selector from (‘#wrapper’) to (‘#wrapper, #wallpaper’) and it’s all working. Thanks a lot James :-)

        • Scratch that last comment, the div I was trying to target was outside of the #wrapper target. I’ve amended the selector from (‘#wrapper’) to (‘#wrapper, #wallpaper’) and it’s all working. Thanks a lot James :-)

  11. So with the Javascript one do you just add the normal:

    googletag.cmd.push(function() { googletag.display(‘div-gpt-ad-137332256584-0′); });

    where ever you want it on the page without having to do anything with it?

    • Oh its stripped most of it out, but you know the bit I mean

    • Yes. Although when it tries to execute the display, there won’t be any adslot defined, so it won’t call the ad.

  12. Rather than hiding the slots that are not used would it not be better to remove them.

    If I gave each different ad div a class as say adsmobile, adsdesktop, adstablet.
    Rather than do
    for each ad to hide which is going to get messy with a lot of them.

    Could I just do:

    var width = window.innerWidth || document.documentElement.clientWidth;
    if (width >= 768) {
    googletag.defineSlot(‘/9999999/myadunit_bottom_728x90′, [728, 90], ‘div-gpt-ad-247324873478-0′).addService(googletag.pubads());
    else if ((width >= 300) && (width < 768)) {
    googletag.defineSlot('/9999999/myadunit_tablet', [468, 60], 'div-gpt-ad-3248237498728-0').addService(googletag.pubads());
    else if (width < 300) {
    googletag.defineSlot('/9999999/myadunit_mobile_only', [300, 250], 'div-gpt-ad-3248237498728-0').addService(googletag.pubads());

    • Yes that would probably be better BUT you are going to run into trouble with execution order.

      If your script executes BEFORE .adsdesktop is setup, then it can’t remove it. If your script executes AFTER .adsdesktop is setup then if you have any

  13. UGH… I am really kinda new to doing this kind of stuff so please bear with me… I am currently running adds on my site by pasting dfp code into the html

    googletag.cmd.push(function() { googletag.display(‘div-gpt-ad-JUMACom_Post_ATF_AS01_125x125′); });

    I ma super confused by your example what is the data-cids?

    • Hi, let me say that dfp is complicated and not an easy way to serve ads. If you’re just dealing with straight Adsense you should just use the new responsive ad units. DFP is great for mixing direct ad sales with adsense as a backup.

      In the sample code, the data-cids is an attribute where you can assign an Adsense channel to an ad unit from your html code. This gets passed into the DFP ad call.

      Remember this is not part of the standard DFP ad tags, but custom code – and you need to know what you are doing.

      • James,

        Thank you for your prompt response. Hey there geek boy the only way a girl is going to learn is for you to put that magic on me :).

        Okay so right now I am actually not filling those ads and was just posting something like the following directly into my html

        googletag.cmd.push(function() { googletag.display('div-gpt-ad-JUMACom_ALL_ATF_UMN_728x90'); });

        And I know please don’t think this is silly but why not some simple idea like…

        if (screen.width > 470) {
        document.write ('googletag.cmd.push(function() { googletag.display("div-gpt-ad-div-gpt-ad-JUMACom_ALL_ATF_UMN_728x90"); });');
        } else {
        document.write ('googletag.cmd.push(function() { googletag.display("div-gpt-ad-JUMACom_ALL_ATF_UMN_320x50"); });');

        • Good idea, but it may not work so well. With DFP you still have to setup TWO ad slots, but then only one is being called.

          Also, if you are using document.write, you will need to put wrap your code in ');

      • i am not exactly sure how to post code on your page :)

  14. I used above mentioned code in my site theme. It works like charm. Thanks James for really helpful code.

    • You’re welcome.

  15. Thanks for the great post!

    I’m a little confused on what the ‘Anchor ads’ are. I don’t see any other information about them in your article other than that they exist, my searches aren’t turning up much, and I can’t find a way to create them on the adsense website.

    • Sorry for sounding cryptic Tom. I’m still waiting on beta testing them, so they definitely aren’t available in adsense yet. As I understand they allow a mobile leaderboard (320×50) to be fixed to the top or bottom of the mobile viewport.

      I’ll definitely be updating this post as soon as get a chance to try them out.

  16. Hello James !

    First of all, good job for your work, I’m using on the website I’m working on and it works great !

    I still have a question for you, I would like yo use multi size ad and I can’t get it working with your JS. I’d like to use something like this [[300, 250], [300, 600], [728, 90]] in one single ad.

    Thanks !

    • Very very good question. I’m in the process now of trying out some new code to show multisize ads. Although so far testing with adsense doesn’t seem to server an 300×600 image ads? I’ll update this post once I get some results.

    • Okay Mathieu, I’ve updated the post. It seems to work okay, although I would like someone else to test and see if it works.

      • Works great James, sorry for de delay, I didn’t have time to try it right away !

        Thanks Alot !

  17. wooooooooooow great

  18. It made sense with mobiles less than 800×480 (2011/2012), but these will be making up a very small portion of mobiles sold in 2014 and beyond. All this choosing ads via size mess is unfortunately for naught.

  19. I have tried google responsive ad unit but get a low CPC but when I use this code my earnings are higher. Thanks for sharing.

    • That’s great… but doesn’t make any sense to me. Unless, the standard responsive ad unit is outputting low performing sizes.

  20. Hello, thanks for ur wonderful tutorials. I’m trying to implement ads (using ur tut) but seems like i’m not getting it right. This is what i’ve done so far. Can u pls tell me where the problem is? I’m not using DFP, just the normal adsense codes. Thanks
    @media screen and (max-width: 640px) {
    .hidden-phone { display: none !important; }
    @media screen and (max-width: 460px) {
    .hidden-phone { display: none !important; }
    @media screen and (max-width: 1110px) {
    .hidden-desktop { display: none !important; }

    My Ads here

    My Ads here

      • I thought there was probably no need to list all the media queries since i’m using only two classes ( .hidden-phone and .hidden-desktop)
        I don’t want to go into DFP yet. Also from ur other article, it means i can’t simply hide/show adsense on the two platforms separately right? (I didn’t really get the part that says: Using Javascript to Remove the Ad Unit on Smaller Viewports)

        —-quite a few questions comes to my mind
        -why can’t google come out with codes that will show/hide depending on the platform? Or maybe something similar to that? (one of their articles says we should’t use the tag, display: none)
        -If this is pretty hard to implement then how do other webmasters do it? Keeps me wondering

        -i’ve spent a lot of time reading about the code implementation and i guess the quickest solution now is to disable the responsive function of the theme on mobile. At least until a clear solution arises.
        -had an offer from few days ago, haven’t responded yet but if i’m to add their ads as well, without any clue on how to switch between mobile and desktop, that will be a big problem.

        • Stone, Google are constantly adding more features to their ad code. As fast as I’ve written these articles, 3 weeks later they come out with some other solution.

          As it stands today, they do offer lots of responsive ad solutions BUT they do not have a feature to simply disable an ad on certain-sized layouts. I do this with a few sites. Maybe I’ll update the other article to make it clearer how I do this.

          They DON’T like display:none as it still calls the ad code and counts as an advertiser impression – not good for the advertiser.

          Oh yeah, DFP is very complicated and keeps getting more tricky to use. The only time you would want to use it is if you have other direct advertisers as well as Adsense or Ad Exchange.

  21. Thank you for all ur replies, that’s so kind of you

  22. Hello

    Thanks for the nice post.
    I’m especially interested in what you did here:
    I wonder, is this even allowed? I’m looking for a solution like this, but I don’t want to risk my adsense account.


    • Hi Anne, specifically which part of the solution are you concerned about?

      • Everytime the ad changes on when changing window size is counted as a new banner impression I think.
        I’m afraid this isn’t allowed with adsense.

        • Excellent question.

          The refresh is a newer feature of DFP, so that’s perfectly valid.

          The official word from Google is this:

          You can refresh on resize for your ad campaigns in DFP, but NOT for Google AdSense. So if you using AdSense as backfill for an Ad unit, you cannot have that unit refresh. HOWEVER, it seems it’s okay to do on orientation change on a mobile device.

  23. Hello, everything is going well here and ofcourse every one is sharing facts, that’s genuinely excellent, keep up writing.

  24. Thank you for your excellent article. I’m interested in implementing solution 3, however I notice on your demo that on the iPhone, the ads are not loading with the page until you rotate the phone. Then, after rotating back it continues to use the now wrong sized ad.

    Do you have any suggestions to get the ad to show when the page loads (I have tried adding a onload event in my tests that is a copy of the resize event with no luck)

    • All working correctly now, and tested on iPhone. Orientation change is working correctly too. The DFP code was throwing an error when requesting a 0x0 sized ad. I’ve altered this to work much better.

  25. I’m not able to find correct “defineSlot”


    How can I find it? what is the relationship between defineSlot and Google Publisher ID or Ad unit ID? how that 8 digits came from?

    Also how to find “div-gpt-ad”
    How these 13 digits came from. is that random?

    Please explain.. thank you so much.

    • That first number is your DFP publisher ID. On DFP you go Inventory / Generate Tags, and select an Ad Unit and it will create the tags.

      The div-gpt-ad-111111111 is created by doing Generate Tags in DFP, and it is a random number that is different every time you Generate Tags.

      As long as the div- number in your defineSlot EXACTLY matched the div- in your Ad slot display code everything will word. If you keep changing these div- numbers it’s easy to make a mistake and the code will not work.

      DFP is complex.

  26. Does this work when opera mini is used to view a blog post that has adsense in it.

    • Adsense does not render on Opera Mini. You would have to look at google’s mobile ad code (for the older WAP sites). This is something I have no experience of.

  27. Hi Author,

    Can I use DFP on Domain by Hosted Adsense Account.

    • I’m really not sure. But to use DFP you need to be able to paste JavaScript into your code.

  28. Hello, been trying the DFP forum forever, and no one can help me with this there. I hope someone would be so kind to help me? So In solution 3 I want to implement the code for reshfreshing ads on viewport resize:

    “var resizeTimer;

    function resizer() {

    window.addEventListener(“resize”, function(){
    resizeTimer = setTimeout(resizer, 250);

    I am using the latest WordPress-theme, I am not savvy at all, would these values go in to the code in my header.php and exactly what values have to be changed and/or added there? Has code to be made/added somewhere else?

    • The code needs to come after the DFP setup code, which should be in your header.php

      This is because we are referencing an adslot (window.Leaderslot). DFP is rather complex to setup, however I do have some nice refreshing code working on the demo page mentioned in the article.

      It also works well on orientation change on mobile devices.

      • I tried the same code (from your example page) to auto refresh the ads, but it don’t work, only after i manually refresh. I use wordpress too, and i had inserted after the dfp config script.
        Can you have any idea what is the error? Whats the code i need to insert?
        I used that:

        var _now = || function() { return new Date().getTime(); };
        var _debounce = function(func, wait, immediate) {
        var timeout;
        return function() {
        var context = this, args = arguments;
        var later = function() {
        timeout = null;
        if (!immediate) func.apply(context, args);
        var callNow = immediate && !timeout;
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);

        document.getElementById(‘width’).innerHTML = window.innerWidth || document.documentElement.clientWidth;

        window.addEventListener(“resize”, _debounce(function() {
        console.log (“Doing refresh”);
        document.getElementById (“width”).innerHTML = window.innerWidth || document.documentElement.clientWidth;
        }, 200)


        • It’s hard to debug without seeing all code on the page. And, to be honest, once you start messing with dfp you need to be reasonably savvy with Javascript.

          Note that you don’t need this line
          document.getElementById (“width”).innerHTML = window.innerWidth || document.documentElement.clientWidth;

          This is only altering an element on the screen to show the viewport size, so you don’t need this.

          • Many thanks! The site is .
            Yeah, the site have many javascripts, that’s a really problem.

            I will try some more tests.


  29. Hi James,

    Wondering if you could help me. We’re in the stage of testing a responsive site project that runs banners via DFP. The banners were implemented but the moment I visit page(s) from the beta site, the banners does not load the first time. It will load only the moment I refresh the page once or somethings the second time.

    Any thoughts?


    • Hard to know without seeing the code. Could it be some kind of timing issue? Are you loading javascript asynchronously? DO you get any errors in the console?

  30. Hii James Foster

    You Bcome a hero to me after seeing this topic

    I am the web emtrepreneur at Basic Steps

    Sir I need Some Help in Protecting the adsense

    Through the Way of Masking with Css Style Upto Limited Time After Clciking On It With Java Script

  31. I’m performing refresh on window resize with Responsive GPT tag. Can you confirm below code is ok to refresh all ads when browser resize? Thanks.

    setInterval(function(){ googletag.pubads().refresh(); }, 480000); });
    googletag.cmd.push(function () {
    setInterval(function(){ googletag.pubads().refresh(); }, 480000);

  32. Hi James,

    (continuing previous message) I’m asking as I’m not sure refresh call should be specific to ad slots. Thanks!!

    • Not quite sure why you’d set such a massive interval time – 480 seconds?

      Also, you don’t want to fire a refresh directly on resize. Resize fires non-stop when you resize a window. You need to use a debounce type function, or set a timeout.

      Also, without including ad slots, it will refresh all ads as I understand it.

  33. Hi James,

    8 minutes refresh rate for all ads is our requirement. That’s why I set it to refresh all ad slots on window re-size (not sure it is the best way).

    I think code fires a refresh directly on re-size of the window. Can you tell how I can use debounce type function or settimeout? which one will be the best?

    Thanks for the quick response.

    • Go take a look at the source of this page:

      Here I’m using refresh with a debounce (borrowed) from the underscore.js library. It works really well. If you look at the console log, rather than being hit by multiple refreshes as you resize the browser – you get just one. If you keep resizing, you’ll get another.

      var _debounce = function(func, wait, immediate) {
      	var timeout;
      	return function() {
      		var context = this, args = arguments;
      		var later = function() {
      			timeout = null;
      			if (!immediate) func.apply(context, args);
      		var callNow = immediate && !timeout;
      		timeout = setTimeout(later, wait);
      		if (callNow) func.apply(context, args);
      window.addEventListener("resize", _debounce(function() {
          console.log ("Doing refresh");
        }, 200)
      • Just wondering, which option do you favour?

        • I think solution 3 is the most robust.

          But to be honest, using DFP is hard work. Great if you are serving a complex mix of ads, but it has become so complex to setup. If you’re just using adsense, better to use the standard adsense responsive code.

  34. James – thanks for the great tutorial.
    I used the new var_debounce script to refresh the ads during resize. As you point out, this script needs to go after the DFP definitions.

  35. Respected Sir,

    i am using WP Mobile Edition plugin for mobile website, i am not able to use Google adsence as the code wich i have genrated from google adsence for the mobile content is not working. Kindly guide me how can i use ads on my mobile website.


    CODE : $value) {
    if (strpos($param, ‘color_’) === 0) {
    google_append_color($google_ad_url, $param);
    } else if (strpos($param, ‘url’) === 0) {
    $google_scheme = ($GLOBALS[‘google’][‘https’] == ‘on’)
    ? ‘https://’ : ‘http://';
    google_append_url($google_ad_url, $param,
    $google_scheme . $GLOBALS[‘google’][$param]);
    } else {
    google_append_globals($google_ad_url, $param);
    return $google_ad_url;

    $google_ad_handle = @fopen(google_get_ad_url(), ‘r’);
    if ($google_ad_handle) {
    while (!feof($google_ad_handle)) {
    echo fread($google_ad_handle, 8192);


    • Hi Bhupinder, unfortunately I’m not able to devote time to debugging code. I suggest you contact the plugin writer.

  36. Thanks for great post James.

    A quick question for option #3 (DFP Responsive Ad Units): – would it be OK to define the DFP ad units with multiple creative sizes within the same unit?

    Instead of:
    var mapLeader = googletag.sizeMapping().addSize([320, 400], [320, 50]).addSize([320, 700], [300, 75])…
    you could do:
    var mapLeader = googletag.sizeMapping().addSize([320, 400], [[320, 50], [320, 75]]).addSize([320, 700], [[320, 75], [320, 100]])…

    This would allow the various sizes (more inventory) to compete within that unit?

    • Yes I believe you can do this (I have not tested this). You would then be able to set different creatives, and allow DFP to choose the best performing. Useful if you have a ton of different creative assets, and almost a full-time job setting everything up!

  37. Thank for the clear write up, James! I’ve spent a good bit of time recently implementing DFP ads in our WordPress theme, and we have the added wrinkle of inserting ad containers dynamically between elements in the WordPress loop via JavaScript. Your suggestion to use data-* attributes on the ad containers themselves really helped. I first implemented using your first suggested solution, then progressed to solution 3, and now I’m refreshing the ads on a breakpoint using mediaCheck ( instead of simply on the ‘resize’ window event. I replaced:

    var resizeTimer;
    function resizer() {
    $(window).resize(function() {
    resizeTimer = setTimeout(resizer, 250);


    media: ‘(max-width: 768px)’,
    both: function() {

    I’ve sent this blog post to others who are struggling with the same stuff. Thanks so much for the resource!

    • Thanks, I’ve had a good look at the Mediacheck script – seems like a great idea to use it with ad refreshing. Ultimately it depends on your ad implementation. It’s conceivable to serve many different creative sizes while still within the same media query breakpoint.

      I wish there were more stats around on orientation change, or how often windows are resized on desktop.

      • Besides the resizing of windows that we do while developing the website, I learned from our digital ads person that salespeople like to show clients about the different ad sizes by resizing their browser live. I don’t expect our actual readers to be resizing, besides orientation changes on tablets or phones.

  38. Hi James,

    My name is Mathew and I’m currently working on implementing the responsive ads and I found your great tutorial, but I’d like to ask few questions.

    The thing is I have DFP Small Business ad units which is filled by PulsePoint ads and while I’m using the mapping solution the banners 728×90 are visiable, but in lower width of viewport they are gone. Whenever I inspect place, there is the iframe of the specified width and height, but the ad itself is missing. should I add more ad tags from pulsepoint to cover smaller banners? the thing is when I’ve entered second banner tag with 320×50 size it was showed only on the biggest desktop resolution instead of my 728×90 and on the smaller it was still gone and shouldn’t be in my opinion. Maybe I am missing something.

    Could you lead me through it? Or just guide where I should ask to find a solution?

    Thanks in advance

  39. I’m at a loss trying to get this to work:

    I’ve put in this:

    var googletag = googletag || {};
    googletag.cmd = googletag.cmd || [];
    (function() {
    var gads = document.createElement(‘script’);
    gads.async = true;
    gads.type = ‘text/javascript';
    var useSSL = ‘https:’ == document.location.protocol;
    gads.src = (useSSL ? ‘https:’ : ‘http:’) +
    var node = document.getElementsByTagName(‘script’)[0];
    node.parentNode.insertBefore(gads, node);

    googletag.cmd.push(function() {

    var mapping1 = googletag.sizeMapping().
    addSize([480, 200], [468, 60]).
    addSize([768, 200], [728, 90]).

    googletag.defineSlot(‘/4049405/728x90_1_archive_hrreview’, [728, 90], ‘div-gpt-ad-1420018633340-0′).addService(googletag.pubads());
    googletag.defineSlot(‘/4049405/728x90_1_home_hrreview’, [728, 90], ‘div-gpt-ad-1420018633340-1′).defineSizeMapping(mapping1).addService(googletag.pubads());
    googletag.defineSlot(‘/4049405/728x90_2_home_hrreview’, [728, 90], ‘div-gpt-ad-1420018633340-2′).defineSizeMapping(mapping1).addService(googletag.pubads());
    googletag.defineSlot(‘/4049405/728x90_3_home_hrreview’, [728, 90], ‘div-gpt-ad-1420018633340-3′).defineSizeMapping(mapping1).addService(googletag.pubads());
    ….. etc

    Is there something I’m missing?

    • Paul, I had a good look and your code looks okay. DFP is a pig to get right, so it maybe that things are not setup correctly on the line item side of things.

  40. James – Thanks for all the work and updates, this site has been incredibly helpful. I am running into an issue with responsive design. My code works when I test banners I created. However, I am trying to get it to work with adsense and display 336×280 on desktop but 320×100 on mobile. Even if I use static sizes for ad sense I can’t seem to get DFP to match the correct size from the ad unit to the creative in ad sense, it just seems to randomly pick one. Do you have any experience or advice on getting the two to play nice together? Thanks!

    • Yeah I have messed around with various combinations. You can use the standard “backfill” with adsense. Or you could even try creating a line item and pasting in the standard adsense ad unit code as the creative (I believe I still do this on one site).

      It’s difficult to diagnose these problems without taking a deep dive into both the front end code and the backend DFP setup.

  41. Hi James,

    I have a question about your example, in the google_console:

    When you refresh the page in a small width window, “Test_Multi_Sidebar” ad is not showing anymore, although the console still says “Ad fetch count: 1″. Is that OK? Doesn’t this count as an impression although the ad didn’t show?
    And I also have a question about a project I am working on. I am using the mapping to show and hide ads for different viewports.

    On desktop I don’t want to show the mobile leaderboard. It works fine, the Ad is not showing up, except that in the Google Console I am getting a warning “Ad unit failed to fetch.”:

    Slot size: EmptyFormat: DivService: DFP
    Ad unit did not fetch.
    Ad unit did not render.
    Ad fetch count: 0
    Iframe type: none
    Ad unit failed to fetch.

    How do I get rid of the warning?

    These are the mapping settings I have used:

    var mappingMobileRibbon = googletag.sizeMapping().
    addSize([991, 200], []).
    addSize([0, 0], [320, 50]).

    Thanks a million!

    • Ad Fetch count is (I believe) just an increment of executing the ad fetch code. It won’t count as an impression.

      Your other warning probably comes from giving it an empty size for your creative. Its fine to have a warning, another option would be to supply a creative size, but not have any line items for it.

  42. Using your example I was able to get almost everything to work in situation 3, thank you!! I’m still sort of at a loss though for how to implement the re-sizing code. I’ve had a look at your live demo but I’m not sure what code to pull from or where to put the line of code you listed in the post. If it’s not too much trouble could you point me in the right direction?

    • Bill, the code uses a debounce function.

      var _now = || function() { return new Date().getTime(); };
      var _debounce = function(func, wait, immediate) {
      var timeout;
      return function() {
      var context = this, args = arguments;
      var later = function() {
      timeout = null;
      if (!immediate) func.apply(context, args);
      var callNow = immediate && !timeout;
      timeout = setTimeout(later, wait);
      if (callNow) func.apply(context, args);

      window.addEventListener(“resize”, _debounce(function() {
      }, 200)

    • Place this code after setting up your ad slots and pubad calls. You will need to assign your defineSlot calls to a variable.

      window.slot1= googletag.defineSlot(
      ‘/1084798/Test_Multi_Width’, [320,50], ‘div-gpt-ad-1393979881710-0′).defineSizeMapping(mapping).addService(googletag.pubads());

  43. I hope I’m asking the right question and on the right site…lol // here’s our page – // we put several Adsense ads in our sidebar but when you resize the browser down, the ads extend out past the sidebar. We’ve tried using both the regular and responsive options from Google adsense and no luck. The ads don’t seem to resize no matter what the size browser/tablet is being used

    Not sure how to fix – any ideas or where I can go for help? I’ve tried google forums but no answers.

    • Alan, that’s normal behavior for Adsense. As at today, they do not auto-refresh or resize. About the best you can do is wrap the ad in a div and set a style of overflow:hidden. That will cut the ad off so that scroll bars don’t show.

  44. Hi, hope you can help me with a question about the div-gpt-ad-RANDOM_NUMBER part of the code

    I’d like to substitute the number for a phrase that describes the ad size and where it’s displayed on my site, so it’s a bit more meaningful.

    Can I customise this to whatever I like once I’ve copied the Tags from the Generate Tags page — being extra careful to make sure they match exactly in the and code?

    Or is there somewhere in the Generate Tag process I can customise this part of the code?

    Or must I keep the same 13 digit number that is automatically generated?


    • Yes you can put whatever you want in there PROVIDED the ad slot declaration ALWAYS matches the actual DIV id in the HTML.

      AFAIK you cannot customise it in the generate tags.

Add a Comment

Your email address will not be published. Required fields are marked *