George Garside Blog

A place of many ramblings about macOS and development. If you find something useful on here, it's probably an accident.

Detect if DFP ad units are on the page

To tell Google Tag Manager that DFP ad units are on the page, a variable will be set up which looks for DOM elements that need to be filled with ads. This variable uses a CSS selector to find these elements, and GTM will store the result in a variable which can be looked at later. To begin, open Google Tag Manager and log in, then select the relevant container. Once you’re in GTM, follow the instructions to set up the variable.

  1. Choose Variables, then select New under User-Defined Variables at the bottom of the page.
    Google Tag Manager User-Defined Variables
  2. Give the variable a name (in this example, we’ll use DFP Ads), then select DOM element as the type.
  3. Under Configure Variable choose CSS selector as the Selection Method and enter the following as the Element Selector:
    This looks for all div elements on the page which have an id beginning div-gpt-ad-. Leave Attribute Name empty.
  4. Make sure your variable looks like the following before continuing with this tutorial.
DFP ads variable in GTM

If you’re interested in precisely what this does, here’s the explanation: Google Tag Manager, once the DOM has loaded, looks through the DOM for all elements matching the CSS selector of div[id^="div-gpt-ad-"]. This CSS selector is looking for all div elements (which the DFP ad tags are, but so are other elements on the page) with an ID beginning with div-gpt-ad-, which is true only for DFP ad tags, but is true for all DFP ad tags. Thus, the content of the variable is the concatenation of these elements. We’ll use this variable to trigger the tag if and only if there are DFP ad units on the page which need DFP ads.

Trigger the DFP ad code

Using the variable we just set up, a trigger can be set up to trigger the DFP ad code (which we haven’t got yet, but we’ll get there).

  1. In Google Tag Manager, select TriggersNew.
  2. Set a name for the trigger (in this example, we’ll use Page contains DFP Ads), and choose Page View as the event.
  3. For the trigger type…
    • Page View: Don’t use this option — DFP will not inject ads correctly with this selected.
    • DOM Ready: Use this if you wish for the DFP ads to be injected as soon as possible.
    • Window Loaded: Use this if you don’t mind a short delay before the ads are injected in return for making sure that all the other elements of your page are loaded first.
  4. Under Fire On, select Some Page Views, then select your variable that you named earlier (in our case, DFP Ads). Choose does not equal and enter null into the box on the right.
GTM trigger: DFP Ads does not equal null
GTM trigger: DFP Ads

Generate the DFP tags for use in GTM

You’ll have to make some changes to the DFP ad code before you can add it though. Before you begin this section, open DoubleClick for Publishers and log in to your account. In this tutorial, we will use a DoubleClick for Publishers Small Business account, however this also works with DoubleClick for Publishers Premium accounts.

  1. In DoubleClick for Publishers, select InventoryGenerate tags. Under Select ad units, click Include all, then Generate Tags.
  2. Set the tag type to Google Publisher Tag, then click Continue. Leave the tag options to their defaults, and click Continue.
  3. Copy and keep the Document header section of the ad tags. You’ll need to add this to the tag in Google Tag Manager. Ignore the Document body section of the ad tags.  

Add the DoubleClick for Publishers ad tag code

It’s time to add the ads from DFP.

  1. In Google Tag Manager, select TagsNew.
  2. Set a name for the tag (in this example, we’ll use Google DFP). For the product, choose Custom HTML Tag.
  3. Paste in the DFP tag you copied in the previous section. We’ll need to make some changes to this code though.
  4. Add the following code before the last closing <script> tag. This loops through all elements with an id beginning with div-gpt-ad- and calls googletag.display(element) on each element.
    var adunits = document.querySelectorAll('div[id^="div-gpt-ad-"]'); for (var i = 0; i < adunits.length; i++) { googletag.cmd.push(function() { googletag.display(adunits[i].getAttribute('id')); }); }
  5. Under Advanced Settings, set Tag firing options to Once per page. This ensures the code is not run multiple times per page.
  6. For Fire On, choose Some Pages, then check the trigger you named earlier (in this example, Page contains DFP Ads is the name of the trigger).
  7. Click Save Tag, then choose Publish in the top-right to publish this code to your site’s GTM tag. Don’t worry that you haven’t implemented the ads yet — the code has no effect without the next section implemented.
DFP inventory: Generate tags

Add the ad units to your HTML

You now need these div-gpt-ad- elements on your page to tell the code above where to inject the ads. You shouldn’t use the code from DFP, as mentioned earlier. Instead, you should take the ID from the tag in the previous section and use this as the id for the div element on your page.

Look in the tag code you added in GTM. You should see lines which look like this:

googletag.defineSlot('/122783354/BlogFooter', [728, 90], 'div-gpt-ad-1455876604709-0').addService(googletag.pubads());
Code language: JavaScript (javascript)

The string I have marked as bold is the id of the div you need to insert in your HTML for this ad unit. The div needs to be empty for this to work. Again, don’t insert the Document body code provided by DFP into the div — use this instead.

<div id="div-gpt-ad-1455876604709-0"></div>
Code language: HTML, XML (xml)

DoubleClick for Publishers is now implemented using Google Tag Manager!

Any pages with DFP ad units should now load using Google Tag Manager! If you have any questions, let me know in the comments below. Here’s an example ad implemented using the method discussed in this article.

Leave a Reply

0 Kev’s avatar

Hi, I don’t understand the part “Add the ad units to your HTML”. I followed all the steps but still cannot see ads showing on the site.

Below is my tag in GTM, I’ve put the ad unit inside, but nothing happens, is that what you mean “Add the ad units to your HTML”? Or I should create a new tag and add the ad unit?

  window.googletag = window.googletag || {cmd: []};
  googletag.cmd.push(function() {
    googletag.defineSlot('/21787810958,22273852169/ai5429.com_pc_top', [[1, 1], [728, 90], [970, 90], [970, 250]], 'div-gpt-ad-1621309906653-0').addService(googletag.pubads());
  var adunits = document.querySelectorAll('div[id^="div-gpt-ad-"]'); 
  for (var i = 0; i < adunits.length; i++) { googletag.cmd.push(function() {               
       googletag.display(adunits[i].getAttribute('id')); }); }
0 derrick’s avatar

Hi! Tell me how to hide double click for publishers network code (Example 21762142461)

There is an example implementation of but I don’t understand how to do it!

Perhaps through the google tag manager (Google Tag Manager)?

Or through this plugin /wp-content/plugins/hm-header-bidding-dfpapi/js/prebid.js

Direction where to go tell me!

0 Brian Thompson’s avatar

does using google tag manager speed up the site then

0 Mojito’s avatar

Thank you for your help, but nothing worked

0 juan’s avatar

so thankful!!! worked correctly

0 Matt’s avatar


I’m having massive issues with the error googletag.defineSlot was called more times than there are DIVs in the DOM. Would disabling SRA fix this?




0 KM’s avatar

How does this work when the code that is supposed to go in the is actually being inserted into the ? As far as I’m aware, GTM cannot insert script into the .

Are there any repercussions to doing it this way, putting all the code into the ?

0 Emye’s avatar

does this work with var mapping ? If yes how to do it then please ?

0 N. M.’s avatar

Thank you for these steps. Most of this still worked once I was able to match up the steps based on the new GTM layout. However, I was not able to figure out what is meant by the last step. Are you saying this code should be added into my own website, replacing the numbers with my own digits? If so where – just at the start of the body on the page(s) we want the ads to show?

0 Bruno Mosciatti’s avatar

Hey, @grgarside:disqus ! I’m trying to setup GTM for my DFP Tags, I have the following head section for the DFP tags.

So I have to add at the end (almost at ) those lines:

var adunits = document.querySelectorAll('div[id^="div-gpt-ad-"]');
for (var i = 0; i < adunits.length; i++) { googletag.cmd.push(function() { googletag.display(adunits[i].getAttribute('id')); }); }

Is that correct? Add it on GTM new Tag?

0 Adam Hirschberg’s avatar

Hey George,

Great Tutorial. I believe with the new GTM updates some things may have changed here. I wanted to see if you could test: for me and see what might be going on? Dom elements look to be read but I can’t get the top ad to fire. I used “ad-unit-” instead of “div-gpt-” for the variable. It shouldn’t be an issue but I’m still waiting for the added

To be removed from my source code here so that I only have the div displayed. If those are removed do you believe this will work?

0 Scott’s avatar

Hi George,

Firstly, thanks so much for this guide – your page is now a recommended resource by DFP support if you weren’t aware 🙂 I’ve followed your instructions but am having a few issues with getting the scripts to execute in the right order through GTM and hoping you can provide some suggestions.

I’ve set up a test page with my ad units through GTM ( and one without GTM/direct to the page ( Through GTM, I get “Exception when invoking function: Cannot read property ‘getAttribute’ of undefined” errors and ‘Ad unit did not fetch’ warnings in the GPT console.

I’ve tried both DOM Ready and Window Loaded trigger types with the same results. DFP support have suggested that the GPT functions are executing before their definition – any thoughts you may have would be really appreciated as there are not many resources around dedicated to this tagging method.


0 Bruno Mosciatti’s avatar

Help me with those erros, please:

gpt.js:4 Failed to execute ‘write’ on ‘Document’: It isn’t possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.

Exception in queued GPT command TypeError: Cannot read property ‘getAttribute’ of undefined

1 Art Supsiri’s avatar

The issue is related to Javascript closures:

The solution I found was to put the for loop INTO the anonymous function:

// Display ads

googletag.cmd.push(function() {

var adunits = document.querySelectorAll(‘div[id^=”div-gpt-ad-“]’);

for (var i = 0; i < adunits.length; i++) {




0 Adam Hirschberg’s avatar

Hey Art thanks for replying with your fix I’m going to give this a go. Did you leave everything else the same here and just move up the loop into the start of the DFP header ?

0 Art Supsiri’s avatar

It’s been a while, but yes, I think so.

0 Adam Hirschberg’s avatar

Anyway you could take a look here:

I was able to get past that error but now it’s saying my divs are not associated to an adunit. Any thoughts?

0 Art Supsiri’s avatar

Adam, I actually put that code right before the the last closing

0 Adam Hirschberg’s avatar

Hey Art,

Yup moved it just now but still getting “adunits failed to fetch”. Can’t seem to find a way past it.

0 Art Supsiri’s avatar

Can you post the GTM code you’re using and the id, dimensions, and ad path of one of your ads?

0 Adam Hirschberg’s avatar

Sure can.

0 Adam Hirschberg’s avatar

@artsupsiri:disqus any idea here?

0 Svetoslav’s avatar

Thanks for the solution, Art! It did the trick for me. Ads went up immediately.

0 Larissa Minarini’s avatar

Nice article.

I don’t know if i did something wrong, but I wasn’t able to set up on my page. I follow all the steps, but in the end, the google console (?googfc) is saying that the “ad unit failed to fetch”. Do you have any toughts in what may be causing this error?

0 Temitayo’s avatar

Hi, Thanks for this post. Please can you clarify the this paragraph “The string I have marked as bold is the id of the div you need to insert in your HTML for this ad unit. The div needs to be empty for this to work. Again, don’t insert the Document body code provided by DFP into the div — use this instead” . where i my to put this id. directly in the website ?

0 Perrine Colignon’s avatar


I may ask a silly question but why do you add DFP tags using GTM? Why is it better? Thanks!

0 fross19’s avatar

Hello from Paris,

I follow each steps and I didn’t succeed to deliver banners on my test page

Do you know if the recent modification in GTM have an impact on the set up you describe ?

I also remove the code


but I still have the following error in the google console

ad slots

“Ad unit failed to fetch.”

page request

“Unknown div id in display(): undefined.”

Here is the code I put in DFP with the piece of code you provide. Do you confirme that this is correct ?

and on my website I have just

Thanks in advance

0 Adrian Galvez’s avatar

This is a great approach , but for example , a wordpress based website with x number of categories or posts for different kind of banners, that are repeating constantly in the whole website, do you think changing :

div-gpt-ad-1455876604709-0 to div-gpt-ad-300×250 .

Would help ? or what you recommend?

Thanks for this

0 Amy’s avatar

Thank you for providing useful tips.

I don’t make sure “Add the ad units to your HTML” sentence.

Why should I use the div code insert in my html instead of DFP’s code?

0 Yiwan Ho’s avatar

Great article, I was wondering if this also work with any other ad units beside DFP? Another question in the “Detect if DFP ad units are on the page” part where you configure the variable I only see “element selector” and “attribute name”. Do I then insert as following:

– element selector = div

– attribute name = test

When i use this on the site?

Thanks in advance!

0 Andrés Gutiérrez’s avatar

@grgarside:disqus Great and very useful article! Tks for sharing….Question, what if I use Tealium as a TMS? I can use the same div[id^=”div-gpt-ad-“] as a JQuery Selector like CSS in GTM? I will be really gratefull if you can help me with this approach. Here’s some info that might be helpful. http://www.lunametrics​.com/blog/2016/08/24/tealium-vs-google-tag-manager/ PS: If you can email me will be awesome!!! Tks again @grgarside:disqus

0 Patrick Garrett’s avatar

George, I’m currently trying your implementation technique and cannot get any ads to show up. There should be a DFP delivered ad below the “Boost Your Bourbon IQ” house ad on this page:

Not quite sure what I’m missing but if you have any ideas please let me know. Thanks!

0 Ekaterina Kempkens’s avatar

Thank you for a great article George! I wanted to let you and others know that with a few minor modifications I was able to get this up and running on our site!

0 Asim Khan’s avatar

Work perfectly

var adunits = document.querySelectorAll(‘div[id^=”div-gpt-ad-“]’);

for (var i = 0; i < adunits.length; i++) {

var myad = adunits[i].getAttribute(‘id’);

console.log(‘Ads : ‘+myad);