Sample Google Publisher Tags

This article provides samples of Google Publisher Tags for desktop and mobile implementations. Learn how to use the Google Tag Generator to generate GPT tags automatically.

This article contains:

Sample of an asynchronous Google Publisher Tag

Below is a sample of the full code that you would use to create an asynchronous Google Publisher Tag. This tag illustrates many of the common features and syntax used in an asynchronous GPT ad request.

1 Html
  • Lines 3-15 is boilerplate that asynchronously loads the GPT JavaScript library used by DFP, using SSL/HTTPS if necessary. This is where the command queue is built which handles the list of functions (generally, ad calls) to be handled asynchronously. Publishers will not need to make changes to this section of the code.

  • (Optional) Lines 16-20 set page-level attributes for ad slots that serve AdSense. If set here, this will override any styles set in the DFP or AdSense. This is not commonly used since you can set this in DFP. For more information about how to set AdSense parameters in GPT, please review the documentation for the .set() function in the Help Centre.

  • Lines 17, 22, 39, 46: If using asynchronous rendering, wrap all javascript - following the initial boilerplate script - in the googletag.cmd.push function on line 17. This will add the function to the command queue to be processed asynchronously with respect to the page load. Read more about the differences between synchronous and asynchronous rendering.

  • Line 23: "/1234/travel/asia/food" specifies the network code (1234) and targeted ad unit (travel/asia/food). You can find your network code in the "Admin" tab of DFP.

    728 90 sets the ad slot creative size. Indicate here which creative size or sizes will be eligible to serve to this ad slot. Indicate multiple sizes using the syntax: [[width1, height1], [width2, height2], [width3, height3]]. All sizes here should also be associated with the targeted ad unit – this will just allow you to narrow the list down based on the specific slot. When using multiple-size ad slots, the slot sizes should be declared in the same order that they appear in DFP. Learn more about slot definition and sequentiality.

  • Lines 23, 26, 37, 40, 44 and 47: "div-gpt-ad-123456789-0") is how we match the ad slots defined in the head to the ad slots on the page (the div tags in the body where the creatives serve). They can be named anything as long as they match, but our tag generator uses "div-gpt-ad-[random number]-0", "div-gpt-ad-[random number]-1" And so on. This is just a tidy way of making them similar but differentiated.

    While random numbers are used here, this is not how GPT uniquely identifies an ad request. That is done behind the scenes with the GPT library. Additionally, these names may be kept the same from page to page so long as there aren't multiple instances of the same div name on the same page.

  • Lines 25, 28, 29 and 30: Set slot-level key-value targeting with the setTargeting (function() { You can associate multiple values with one key, as in the first example: ("key". ["value1", "value2", "value3"]). If you want to target multiple keys, call the function multiple times as shown in the second case (gender=male and age=20-30). For more information about how to set key-value parameters in GPT, please review the documentation for the .setTargeting() function as well as our article on "Setting targeting and sizes with GPT". 

  • Line 30: googletag.pubads().setTargeting("topic","basketball"); sets the page-level key-value targeting. Note that when customised targeting is configured using page-level customised targeting, all ad slots will inherit this customised targeting. Like slot-level customised targeting, you can associate multiple values with one key: ("key". ["value1", "value2", "value3"]). For more information about how to set key-value parameters in GPT, please review the documentation for the setTargeting function as well as our article on Setting targeting and sizes with GPT.

  • Line 31:     googletag.pubads().enableSingleRequest(); enables Single Request Architecture (SRA). Include this line if you want to call all ad slots on the page in one call (allows for guaranteed roadblocks and, by consolidating ads into one call, may have performance benefits for your page). Why would anyone not use SRA? Currently, SRA does not support DoubleClick tag (InRed tag) rewind or Google Programmable Ads (GPA).

  • Line 37: (Optional) style="width: 728px; height: 90px" is the size that the element will take before the creative is rendered. If using multi-size tags, it's best to omit this (in that case, the size of the element will take on the size of the selected creative once rendered) or – if you choose to use it – make both dimensions large enough to contain the largest eligible creative. But for single size ad tags, this can be used to expand the container element until the creative loads so that other page elements do not shift when the creative renders.

2 <head>
3 <script type="text/javascript">
4 var googletag = googletag || {};
5 googletag.cmd = googletag.cmd || [];
6   (function() {
7     var gads = document.createElement("script");
8 gads.async = true;
9     gads.type = "text/javascript";
10     var useSSL = "https:" == document.location.protocol;
11     gads.src = (useSSL ? "https:" : "http:") + "//www.googletagservices.com/tag/js/gpt.js";
12     var node =document.getElementsByTagName("script")[0];
13 node.parentNode.insertBefore(gads, node);
14    })();
15 </script>
16 <script type="text/javascript">
17   googletag.cmd.push(function() {
18     googletag.pubads().set("adsense_background_colour", "FFFFFF");
19   });
20 </script>
21 <script>
22   googletag.cmd.push(function() {
23 {0}{/0}    googletag.defineSlot("/1234/travel/asia/food", [728, 90], "div-gpt-ad-123456789-0"){0}{/0}
24       .addService(googletag.pubads())
25       .setTargeting("interests", ["sports", "music", "films"]);
26 {0}{/0}    googletag.defineSlot("/1234/travel/asia/food", [[468, 60], [728, 90], [300, 250]], "div-gpt-ad-123456789-1"){0}{/0}
27       .addService(googletag.pubads())
28       .setTargeting("gender", "male")
29       .setTargeting("age", "20-30");
30     googletag.pubads().setTargeting("topic","basketball");
31     googletag.pubads().enableSingleRequest();
32     googletag.enableServices();
33   });
34 </script>
35 </head>
36 <body>
37   <div id="div-gpt-ad-123456789-0" style="width: 728px; height: 90px">
38     <script type="text/javascript">
39       googletag.cmd.push(function() {
40       googletag.display("div-gpt-ad-123456789-0");
41       });
42     </script>
43   </div>
44     <div id="div-gpt-ad-123456789-1">
45     <script type="text/javascript">
46       googletag.cmd.push(function() {
47          googletag.display("div-gpt-ad-123456789-1");
48       });
49     </script>
50   </div>
51 </body>
52 </html>
 

Sample of a synchronous Google Publisher Tag

Below is a sample of the full code that you would use to create a synchronous Google Publisher Tag. This tag illustrates many of the common features and syntax used in a synchronous GPT ad request.

For more information about how to generate Google Publisher Tags, read our article on generating tags within DFP.

1 <html>
  • Lines 3-10 is boilerplate that asynchronously loads the GPT JavaScript library used by DFP, using SSL/HTTPS if necessary. This is where the command queue is built which handles the list of functions (generally, ad calls) to be handled asynchronously. Publishers will not need to make changes to this section of the code.

  • (Optional) Lines 11-13 set page-level attributes for ad slots that serve AdSense. If set here, this will override any styles set in the DFP or AdSense. This is not commonly used since you can set this in DFP. For more information about how to set AdSense parameters in GPT, please review the documentation for the .set() function in the Help Centre.

  • Lines 15 and 18: "/1234/travel/asia/food" specifies the network code (1234) and targeted ad unit (travel/asia/food). You can find your network code in the "Admin" tab of DFP.

    728 90 sets the ad slot creative size. Indicate here which creative size or sizes will be eligible to serve to this ad slot. Indicate multiple sizes using the syntax: [[width1, height1], [width2, height2], [width3, height3]]. All sizes here should also be associated with the targeted ad unit – this will just allow you to narrow the list down based on the specific slot. When using multiple-size ad slots, the slot sizes should be declared in the same order that they appear in DFP. Learn more about slot definition and sequentiality.

    Lines 15, 18, 29, 31, 34 and 36: "div-gpt-ad-123456789-0") is how we match the ad slots defined in the head to the ad slots on the page (the div tags in the body where the creatives serve). They can be named anything as long as they match, but our tag generator uses "div-gpt-ad-[random number]-0", "div-gpt-ad-[random number]-1" And so on. This is just a tidy way of making them similar but differentiated.

    While random numbers are used here, this is not how GPT uniquely identifies an ad request. That is done behind the scenes with the GPT library. Additionally, these names may be kept the same from page to page as long as there aren't multiple instances of the same div name on the same page.

  • Lines 17, 20, 21 and 22: (Optional) Set slot-level key-value targeting with the setTargeting (function() { You can associate multiple values with one key, as in the first example: ("key". ["value1", "value2", "value3"]). If you want to target multiple keys, call the function multiple times as shown in the second case (gender=male and age=20-30). For more information about how to set key-value parameters in GPT, please review the documentation for the .setTargeting() function as well as our article on "Setting targeting and sizes with GPT". 

  • Line 22: googletag.pubads().setTargeting("topic","basketball"); sets the page-level key-value targeting. Note that when customised targeting is configured using page-level customised targeting, all ad slots will inherit this customised targeting. Like slot-level customised targeting, you can associate multiple values with one key: ("key". ["value1", "value2", "value3"]). For more information about how to set key-value parameters in GPT, please review the documentation for the setTargeting function as well as our article on Setting targeting and sizes with GPT.

  • Line 23:     googletag.pubads().enableSingleRequest(); enables Single Request Architecture (SRA). Include this line if you want to call all ad slots on the page in one call (allows for guaranteed roadblocks and, by consolidating ads into one call, may have performance benefits for your page). Why would anyone not use SRA? Currently, SRA does not support DoubleClick tag (InRed tag) rewind, nor Google Programmable Ads (GPA).

  • Line 24: To render the creatives synchronously, add googletag.pubads().enableSyncRendering();. This instructs the service to wait for each ad request to complete before continuing with rendering the page.

  • Line 29: (Optional) style="width: 728px; height: 90px" is the size that the element will take before the creative is rendered. If using multi-size tags, it's best to omit this (in that case, the size of the element will take on the size of the selected creative once rendered) or – if you choose to use it – make both dimensions large enough to contain the largest eligible creative. But for single size ad tags, this can be used to expand the container element until the creative loads so that other page elements do not shift when the creative renders.

2 <head>
3 <script type="text/javascript">
4   (function() {
5 var useSSL = "https:" == document.location.protocol;
6 var src = (useSSL ? 'https:' : 'http:') +
7 '//www.googletagservices.com/tag/js/gpt_mobile.js';
8   document.write('<scr' + 'ipt src="' + src + '"></scr' + 'ipt>');
9   })();
10 </script>
11 <script type="text/javascript">
12     googletag.pubads().set("adsense_background_colour", "FFFFFF");
13 </script>
14 <script>
15     googletag.defineSlot("/1234/travel/asia/food", [728, 90], "div-gpt-ad-123456789-0")
16       .addService(googletag.pubads())
17       .setTargeting("interests", ["sports", "music", "movies"]);
18     googletag.defineSlot("/1234/travel/asia/food", [[468, 60], [728, 90], [300, 250]], "div-gpt-ad-123456789-1")
19       .addService(googletag.pubads())
20       .setTargeting("gender", "male")
21       .setTargeting("age", "20-30");
22     googletag.pubads().setTargeting("topic","basketball");
23     googletag.pubads().enableSingleRequest();
24     googletag.pubads().enableSyncRendering();
25     googletag.enableServices();
26 </script>
27 </head>
28 <body>
29   <div id="div-gpt-ad-123456789-0" style="width: 728px; height: 90px">
30     <script type="text/javascript">
31       googletag.display("div-gpt-ad-123456789-0");
32     </script>
33   </div>
34   <div id="div-gpt-ad-123456789-1">
35     <script type="text/javascript">
36       googletag.display("div-gpt-ad-123456789-1");
37     </script>
38   </div>
39 </body>
40 </html>
 

If you aren't able to edit the headers of your web pages

You can define ad units inline in each ad tag as the page loads. Although this is not the recommended tagging methodology, you may need to do this if you don't have the ability to edit the header.

Because the ad tag uses the GPT JavaScript library, you'll need to include the code that loads the library before you include the ad tag code. The code that loads the library is included in the below example.

To define an ad slot as the page loads, use the following examples:

Asynchronous GPT example

Call the GPT JavaScript library

<script type="text/javascript">
 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>

Sample ad tag 1: Asynchronous inline tag (this method does not support SRA)

<div id="div-gpt-ad-1234567891234-0">
  <script type='text/javascript'>
    googletag.cmd.push(function() {
      googletag.defineSlot('/1234/sports/football', [728, 90],'div-gpt-ad-1234567891234-0')
        .addService(googletag.pubads())
        .setTargeting("Gender", "Male");
      googletag.enableServices();
      googletag.display('div-gpt-ad-1234567891234-0');
  });
  </script>
</div>

Sample ad tag 2: Asynchronous condensed inline tag (this method does not support SRA or ad-slot level targeting)

<div id='div-gpt-ad-1234567891234-0'>
  <script type='text/javascript'>
    googletag.cmd.push(function() {
      googletag.pubads().display('/1234/sports/football', [728, 90], 'div-gpt-ad-1234567891234-0');
    });
  </script>
</div>
Synchronous GPT example

Call the GPT JavaScript library

<script type="text/javascript">
 (function() {
   var useSSL = 'https:' == document.location.protocol;
   var src = (useSSL ? 'https:' : 'http:') + '//www.googletagservices.com/tag/js/gpt.js';
   document.write('<scr' + 'ipt src="' + src + '"></scr' + 'ipt>');
 })();
</script>

Sample ad tag 1: Synchronous inline tag (this method does not support SRA)

<div id='div-gpt-ad-1234567891234-0'>
  <script type='text/javascript'>
    googletag.defineSlot('/1234/sports/football', [728, 90],'div-gpt-ad-1234567891234-0')
      .addService(googletag.pubads())
      .setTargeting("Gender", "Male");
    googletag.pubads().enableSyncRendering();
    googletag.enableServices();googletag.display('div-gpt-ad-1234567891234-0');
  </script>
</div>

Sample ad tag 2: Inline tags, condensed form (this method does not support SRA or ad slot-level targeting)

<div id='div-gpt-ad-1234567891234-0'>
  <script type='text/javascript'>
    googletag.pubads().display('/1234/sports/football', [728, 90], 'div-gpt-ad-1234567891234-0');
  </script>
</div>

Override AdSense formatting at the page level (optional)

In most cases, you'll have already set formatting for your AdSense ads in DFP or AdSense. However, if you want to override this formatting at the individual page level, you can insert the following code into your tags.

For asynchronous tags:

<script>
  googletag.cmd.push(function() {
    googletag.pubads().set("adsense_background_colour", "FFFFFF");
  });
</script>

For synchronous tags:

<script>
  googletag.pubads().set("adsense_background_colour", "FFFFFF");
</script>

Use a non-JavaScript GPT tag to create a 1 x 1 tracking pixel

To create an impression tracker with GPT:

  1. Create a new ad unit or choose an existing one with which to track the impression count.

  2. Create a 1 x 1 line item and add a transparent pixel customised or third-party creative to it.

  3. Target the 1 x 1 line item to the tracking ad unit.

  4. Create a non-JavaScript GPT tag that calls the impression pixel.

    Below is a sample of the code that you would add to the creative code to create a 1 x 1 impression tracker using the non-JavaScript tag format:

    <img src='http://pubads.g.doubleclick.net/gampad/ad?iu=/1234/ad_unit&sz=1x1&t=&c=12345678'/>
  5. Use the impression pixel tag in one of two ways:

    • Add the tag to a customised or third-party creative that will be delivered onto the page: In the creative's "Settings" tab, add the tag to the top of the "Code snippet" box.

    • Add the tag directly to the web page.

For more information about how to generate non-JavaScript based URLs, read our article about serving ads to a non-JavaScript environment.