Igor Kromin |   Consultant. Coder. Blogger. Tinkerer. Gamer.

I've used Google DoubleClick for Publishers on a number of my sites and when it came to thinking about monetising my new project (AtariGamer) that was my goto choice once again. However, compared to my previous approaches, I wanted to do things differently over at AtariGamer. My goal was to try and use well established web app frameworks as much as possible and so I decided to use Backbone.js for all dynamic UI generation. This was to include all of the ads. I also used jQuery to make some things simpler.

To get DFP ads working with Backbone.js I had to create a template, model and a view. My first implementation of this failed spectacularly due to DFP's use of closures for its command execution. I learned from that mistake and rewrote the code and came up with something that worked pretty well.

The DFP reference was useful documentation in helping me resolve the issues I came across. In this article I will not cover basics such as setting up ad units or adding the googletag code to your pages - these are covered in my previous articles: How to use Google AdSense on infinite scroll web pages and Using Google DFP with AdSense on responsive pages. Have a look at those to get up to speed if you're not familiar with DFP.

So lets first look at the template. I've simplified this one from my actual implementation (I require the use of tables for ads over at AtariGamer). This template keeps things simple and down to the bare essentials. Here it is...
 HTML body
<script type="text/template" id="ad-template">
<div id="<%- id %>"></div>
</script>


That's all there's to it! The template of course goes somewhere inside the HTML body element.

Next up is the JavaScript for the Backbone model and view. These take care of encapsulating configuration and ad data and also generating ad elements for rendering,
 JavaScript
DfpAdModel = Backbone.Model.extend({
defaults: function() {
/* update pubId, adUnitCode and size to suit your DFP account details */
this.set('pubId', '12345678');
this.set('adUnitCode', 'MyAdUnit');
this.set('size', [728, 90]);
/* don't change the id */
this.set('id', 'dfpslot' + DfpAdModel.dfpSlotId++);
},
dfp: function() {
var adUnitPath = '/' + this.get('pubId') + '/' + this.get('adUnitCode');
var adSize = this.get('size');
var id = this.get('id');
if (typeof googletag !== 'undefined') {
googletag.cmd.push(function() {
var slot = googletag.defineSlot(adUnitPath, adSize, id)
.addService(googletag.pubads());
googletag.display(id);
googletag.pubads().refresh([slot]);
});
}
}
},
{ dfpSlotId: 1 }
);
DfpAdView = Backbone.View.extend({
tagName: 'div',
template: _.template($('#ad-template').html()),
render: function () {
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});




The model takes care of storing DFP account details and keeping track of the ad slot ID. This is also where the googletag code is placed. The slot ID is kept track of by using a static variable and incrementing it each time a new model is created. This way each new instance of a model gets a unique slot ID assigned.

The view simply looks up the template, passes it the model and creates the HTML elements required.

So that's the template, model and view all taken care of. What's left is making it all work together and adding it to the DOM. For that my code looks something like this...
 JavaScript
var model = new DfpAdModel();
$('body').append((new DfpAdView( { model: model })).render().el);
model.dfp();


The code above creates a new model and view and appends it to the HTML body. The view can of course be inserted anywhere else in the DOM, it's just simpler to use $('body') for this example. Once the view is added, the dfp() function is called on the model to execute the googletag code that fetches and renders the ad.

This code can be repeated anywhere else a new DFP ad (in a new ad slot) should be added. This is great for infinite scroll pages or pages where ads need to be inserted at regular intervals. I've also used it on some pages with static content simply because it was easy to insert ads this way.

Add CSS to suit and you've got a very reusable Backbone.js model and view that will let you insert DFP ads with ease.

-i

A quick disclaimer...

Although I put in a great effort into researching all the topics I cover, mistakes can happen. Use of any information from my blog posts should be at own risk and I do not hold any liability towards any information misuse or damages caused by following any of my posts.

All content and opinions expressed on this Blog are my own and do not represent the opinions of my employer (Oracle). Use of any information contained in this blog post/article is subject to this disclaimer.
Hi! You can search my blog here ⤵
NOTE: (2022) This Blog is no longer maintained and I will not be answering any emails or comments.

I am now focusing on Atari Gamer.