Igor's Blog

I've been using Google DFP instead of AdSense on a number of sites that I run because it relaxes some of the AdSense rules and more importantly gives you fuller control of your ad placement. For example you can easily place AdSense ads on infinite scroll pages using DFP, which can't be done with standard AdSense code. One place that DFP falls short however is the ability to use responsive ads. This example shows how with a bit of extra code it is possible to make DFP ads somewhat more responsive friendly.

In case you're going to say that DFP actually supports the 'fluid' ad size, you would be right, but this ad size does not work when using DFP with AdSense as a fallback. Further, the 'Smart Banner' ad style is only available for mobile, so that's a no go either.
dfp_resp1.png


The image below shows the desired results. I wanted to be able to select the most appropriate ad size for any given container based on that container's width. This isn't exactly responsive but if your container is the width of your page it is as close as it gets. This approach works very well if you don't expect ads to resize if the browser window is resized. The ad size is picked when the ad is first inserted into a page and remains static, this still allows the same responsive page to contain ads that work equally well on desktop as on mobile.
dfp_resp2.png


So lets see how you can implement this. The first step is to select all of the possible ad sizes. I think horizontal banner sizes work best so that's what I did for my example. This is done in the DFP Inventory console for the ad unit you wish to use on your page.
dfp_resp3.png


Now for some HTML. This creates an 800px container DIV with another DIV element inside that will hold the DFP ad slot.


 HTML
<div style=" width: 800px;">
<div id="responsive_dfp1" style="background-color:#e5e599;margin: 0 auto;"></div>
</div>


Don't forget to include DFP code inside the <head> element.
 DFP Code
<!-- Google DFP -->
<script>
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:') +
'//www.googletagservices.com/tag/js/gpt.js';
var node = document.getElementsByTagName('script')[0];
node.parentNode.insertBefore(gads, node);
})();
</script>


Then for some JavaScript. Here DFP values for the publisher ID, ad unit name and all of the ad sizes that were picked in the DFP Inventory console are set up. Note the array keys in the dfpSizes array are the widths of the ad and the values are the full ad dimensions.
 JavaScript
/* Google DFP configuration */
dfpPublisherId = '99999999';
dfpAdUnitCode = 'YourAdUnitCode';
/* Configured ad unit sizes (from DFP Inventory console) */
var dfpSizes = {
234: [234, 60],
300: [300, 75],
320: [320, 50],
468: [468, 60],
728: [728, 90],
970: [970, 90]
};


The next bit of JavaScript initialises DFP and creates an ad slot for the 800px container. Note that the DFP slot name used, 'responsive_dfp1', is the same as on the inner DIV of the 800px container.
 JavaScript
/* initialise Google DFP, but disable initial ad loading */
googletag.cmd.push(function() {
googletag.pubads().enableSingleRequest();
googletag.pubads().disableInitialLoad();
googletag.enableServices();
});
/* create example ad slots */
makeDfpSlot('responsive_dfp1');



Everything so far has been setup and initialisation. The makeDfpSlot() function is where all the real magic happens. That function looks like this:
 JavaScript
function makeDfpSlot(slotId) {
var slotElement = document.getElementById(slotId);
var parentElement = slotElement.parentElement;
var parentStyle = getComputedStyle(parentElement);
var maxWidth = parseInt(parentStyle.width);
/* find the most suitable ad width for parent container width */
var pickedWidth;
for (var idx in dfpSizes) {
if (idx != undefined && idx <= maxWidth) {
if (pickedWidth == undefined) {
pickedWidth = idx;
}
else {
if (pickedWidth < idx) {
pickedWidth = idx;
}
}
}
}
/* adjust ad container dimensions to ad dimensions */
var size = dfpSizes[pickedWidth];
slotElement.style.width = size[0] + 'px';
slotElement.style.height = size[1] + 'px';
/* create the ad slot and load ad content */
googletag.cmd.push(function() {
var slot = googletag.defineSlot("/" + dfpPublisherId + "/" + dfpAdUnitCode, size, slotId)
.addService(googletag.pubads());
googletag.display(slotId);
googletag.pubads().refresh([slot]);
});
}


What the above function does is find the DFP slots's DIV parent width. Then, based on that width and the ad sizes configured in the dfpSizes array it picks the largest ad size that would fit inside the parent container. Once the ad size is picked, the DFP slot DIV dimensions are adjusted, a new slot is created and refreshed so an ad will show.

You can find a fully worked example of the above on my GitHub repository here.

This is more work than standard AdSense code but if you combine it with infinite scroll pages it becomes very powerful.

-i

, , , , ,
About — I'm an enthusiastic software engineer and consultant interested in many fields including J2EE, programming, electronics, 3D printing, video games, wood working and gardening.
See my Resume for more information.
The views expressed in this blog are my own and not those of my employer.
comments powered by Disqus
My other posts you may like...
Programming, DIY, Games, Hacks, Tech and more.
Follow me on...
Current and Past Projects
See my Resume

Subscribe


RSS Feed

My Other Web Sites

Igor and Elise's Travels
Riverside Expressway Cam
StrFunc() Online
300 George St Blogumentary
Guru JSON-RPC Tester
Extrudifier Object Designer

Recent Blog Posts

Older versions of JD-GUI crashing on macOS Sierra

How does Seeed Fusion stack up as a low budget PCB fab

Where to find the last item (Robbie's lost lyrics) in GravityFalls Lake level

Detecting print requests to print contents of a DIV with JavaScript

Using Google DFP with AdSense on responsive pages

How to change the email subject line in Gmail

Force PHP GD library to load JPEG images that have invalid data

How to uninstall Samsung Smart Switch from your Mac

Facebook adds weather forecasts but forgets to adjust them to your time zone

No sound or microphone when answering calls on an iPhone

Recent Galleries

Space Food - Chocolate Ice Cream with Chocolate Chips

Legeod Star Wars AT-DP kit

DIY spare parts computer build with a RAIDMAX Anura case

Fake 'Lepin' brand Lego packaging

Hardwood garden bench with clear resin void filler

Fixing a 3D printer extruder that stopped heating up

Easily increase disk space in a Lenovo Ideapad 100S 14" laptop with an M.2 SSD

Making a multi-piece 3D printed solder spool holder stand

DIY indoor apartment grow light wiring

Good Friday Electronics fun Easter Bunny LED PCB Kit IBEABU-01.0

Top Categories

Blogs I follow

Matt Moores Blog
Georgi's FlatPress Guide
Perplexing Permutations
The Security Sleuth

Friends

RAWS Parts Online
Alpha Dimensions Hosting
Kristensen Photography
Ilia Rogatchevski
Travelling Fairy

Blog Activity

Blog Activity
Follow me on... 
     
...or subscribe for updates!

Don't show this again