How to Use Google DFP and Adsense on a Responsive Website

rwd

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 CaffeineInformer.com 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.
</div>

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 = 'http://www.googletagservices.com/tag/js/gpt.js';
	var node = document.getElementsByTagName('script')[0];
	node.parentNode.insertBefore(gads, node);
})();
></script>

 

Then after this:


$(document).ready(function(){
	var dfpslots=$("#wrapper").find(".adslot").filter(":visible"),
	i=0,
	slot= new Array();

	if (dfpslots.length) {
		googletag.cmd.push(function() {
			$(dfpslots).each(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'));
				i++
			});

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

			$(dfpslots).each(function(){
				googletag.display($(this).attr('id'));
			});
		});
	}
});

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:


[...]
			$(dfpslots).each(function(){
			 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'));
				i++
			});
[...]

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());
	$("#div-gpt-ad-3248237498728-1").hide();
}
else if ((width >= 300) && (width < 768)) {
	googletag.defineSlot('/9999999/myadunit_mobile_only', [300, 250], 'div-gpt-ad-3248237498728-1').addService(googletag.pubads());
	$("#div-gpt-ad-3248237498728-2").hide();
}
googletag.pubads().enableSingleRequest();
googletag.enableServices();
});
// ]]></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]).
		build();
	
	window.LeaderSlot= googletag.defineSlot('/1084798/Test_Multi_Width', [320,50], 'div-gpt-ad-1393979881710-0').
		defineSizeMapping(mapLeader).
		addService(googletag.pubads());

	googletag.enableServices();

});

Further on our ad slot declaration is standard DFP:



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).

In DFP
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.

Issues
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.

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.

UPDATE: Sep 13 – New Anchor Ads.
UPDATE: Oct 13 – New DFP responsive code.
UPDATE: Mar 14 – Complete overhaul.

James Foster
James makes websites, you can follow him on @exisweb.
Filed under Responsive Design
Created: March 13, 2013, updated on March 23, 2014

90 Comments

  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.

    Thanks.

    • 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?

    Thanks!

    • 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.

    https://github.com/mattnish/rad

    • 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 https://support.google.com/dfp_sb/answer/181070

      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(document).ready(function(){
    jQuery(window).load(function() {
    var dfpslots=jQuery(“#wrapper”).find(“.adslot”).filter(“:visible”),
    i=0,
    slot= new Array();
    if (dfpslots.length) {
    googletag.cmd.push(function() {
    jQuery(dfpslots).each(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’));
    i++
    });
    googletag.defineSlot(‘/4856165/BackgroundWallpaper’, [1, 1], ‘background-wallpaper’).addService(googletag.pubads());
    googletag.pubads().setTargeting(‘SiteType’, ‘website’);
    googletag.pubads().setTargeting(‘AreaType’, );
    googletag.enableServices();
    jQuery(dfpslots).each(function(){
    googletag.display(jQuery(this).attr(‘id’));
    });
    });
    }
    });
    });

    Thanks,

    James

    • 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.

        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 :-)

        • 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
    $(“#div-gpt-ad-247324873478-0″).hide();
    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());
    $(‘.adsmobile’).remove();
    $(‘.adstablet’).remove();
    }
    else if ((width >= 300) && (width < 768)) {
    googletag.defineSlot('/9999999/myadunit_tablet', [468, 60], 'div-gpt-ad-3248237498728-0').addService(googletag.pubads());
    $('.adsmobile').remove();
    $('.adsdesktop').remove();
    }
    else if (width < 300) {
    googletag.defineSlot('/9999999/myadunit_mobile_only', [300, 250], 'div-gpt-ad-3248237498728-0').addService(googletag.pubads());
    $('.adsdesktop').remove();
    $('.adstablet').remove();
    }

    • 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; }
    DIVs

    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 media.net 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: http://exisweb.net/test-dfp-ads
    I wonder, is this even allowed? I’m looking for a solution like this, but I don’t want to risk my adsense account.

    Thanks

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

      • Everytime the ad changes on http://exisweb.net/test-dfp-ads 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 0×0 sized ad. I’ve altered this to work much better.

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

    googletag.defineSlot(‘/88888888

    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”
    div-gpt-ad-1111111111111-0
    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() {
    googletag.pubads().refresh([window.Leaderslot]);
    }

    window.addEventListener(“resize”, function(){
    clearTimeout(resizeTimer);
    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.

  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?

    Thanks.

    • 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.

    $(window).resize(function(){
    googletag.pubads().refresh();
    setInterval(function(){ googletag.pubads().refresh(); }, 480000); });
    googletag.cmd.push(function () {
    googletag.display(“div-728×90″);
    googletag.display(“div-Top300x250″);
    googletag.display(“div-Bot300x250″);
    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: http://exisweb.net/test-dfp-ads

      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;
      		clearTimeout(timeout);
      		timeout = setTimeout(later, wait);
      		if (callNow) func.apply(context, args);
      	};
      };
      
      window.addEventListener("resize", _debounce(function() {
          console.log ("Doing refresh");
          googletag.pubads().refresh([window.slot1,window.slot2]);
        }, 200)
      );
      

Add a Comment

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