Search
Clear search
Close search
Google apps
Main menu

Google Publisher Tag samples

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

This article contains:

DoubleClick for Publishers: GPT Implementation (4:57)

Example of an asynchronous Google Publisher Tag

Here is a sample of the full code for creating an asynchronous Google Publisher Tag, illustrating many of the common features and syntax in an asynchronous GPT ad request. Learn more about generating tags in DFP

1 <html>
  • Lines 3-8 is boiler-plate that asynchronously loads the GPT library used by DFP, using SSL/HTTPS. This is where the command queue is built, which handles the list of functions (generally, ad calls) to be handled asynchronously. You don't need to edit this section of code.

  • (Optional) Lines 9-13 set page-level attributes for ad slots that serve AdSense. Changing these attributes overrides overrides any styles set in DFP or AdSense. This function is not commonly used, since you can set this in DFP. The developer documentation for the .set() function describes how to set AdSense parameters in GPT.

  • Lines 10, 15, 32, 39: When using asynchronous rendering, wraps all scripts -- following the initial boilerplate -- in the googletag.cmd.push function on line 10. This adds the function to the command queue to be processed asynchronously when the page loads. Learn the differences between synchronous and asynchronous rendering.

  • Line 16: "/1234/travel/asia" specifies the network code (1234) and targeted ad unit (travel/asia). Find your network code in the "Admin" tab of DFP.

    [728, 90] sets the ad slot creative size. Indicate multiple sizes using the syntax: [[width1, height1], [width2, height2], [width3, height3]]. Associate all sizes here with the targeted ad unit, allowing you to narrow the list down based on the specific slot. When using multiple size ad slots, declare the slot sizes in the same order that they appear in DFP. Learn more about slot definition and sequentiality.

  • Lines 16, 19, 30, 33, 37, and 40: "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 the naming convention of "div-gpt-ad-[random number]-0", "div-gpt-ad-[random number]-1" and so on. Use the same <div> ID consistently for a given position on a page, as it is used for optimization in a wide range of areas.

    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 the same from page to page as long as there aren't multiple instances of the same div name on the same page.

    Learn more about the DFP inventory structure, ad unit hierarchy, and how ad units inherit targeting in the inventory overview.

  • Lines 18, 21, 22, and 23: 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"]). To target multiple keys, call the function multiple times, as in the second case: (gender=male and age=20-30).

    The developer documentation for the .setTargeting() function describes how to set key-value parameters in GPT. Learn more about setting targeting and sizes with GPT

  • Line 23: googletag.pubads().setTargeting("topic","basketball"); sets page-level key-value targeting. When configuring targeting with page-level key-values, all ad slots inherit this targeting. Like slot-level key-values, you can associate multiple values with one key: ("key", ["value1", "value2", "value3"]).

  • Line 24: googletag.pubads().enableSingleRequest(); enables Single Request Architecture (SRA). Include this line to call all ad slots on the page in one call (allows for guaranteed roadblocks, and may have performance benefits for your page). Currently, SRA doesn't support Google Programmable Ads (GPA).

  • Line 30: (Optional) style="width: 728px; height: 90px" is the size that the element takes before the creative is rendered. If using multi-size tags, we recommend either omitting this (in that case, the size of the element takes the size of the selected creative when rendered) or making both dimensions large enough to contain the largest eligible creative. For single size ad tags, use this parameter to expand the container element until the creative loads so that other page elements don't shift when the creative renders.

2 <head>
3 <script async="async" src="https://www.googletagservices.com/tag/js/gpt.js">
4 </script>
5 <script>
6   var googletag = googletag || {};
7   googletag.cmd = googletag.cmd || [];
8 </script>
9 <script>
10   googletag.cmd.push(function() {
11     googletag.pubads().set("adsense_background_color", "FFFFFF");
12   });
13 </script>
14 <script>
15   googletag.cmd.push(function() {
16     googletag.defineSlot("/1234/travel/asia", [728, 90], "div-gpt-ad-123456789-0")
17       .addService(googletag.pubads())
18       .setTargeting("interests", ["sports", "music", "movies"]);
19     googletag.defineSlot("/1234/travel/asia", [[468, 60], [728, 90], [300, 250]], "div-gpt-ad-123456789-1")
20       .addService(googletag.pubads())
21       .setTargeting("gender", "male")
22       .setTargeting("age", "20-30");
23     googletag.pubads().setTargeting("topic","basketball");
24     googletag.pubads().enableSingleRequest();
25     googletag.enableServices();
26   });
27 </script>
28 </head>
29 <body>
30   <div id="div-gpt-ad-123456789-0" style="width: 728px; height: 90px">
31     <script>
32       googletag.cmd.push(function() {
33          googletag.display("div-gpt-ad-123456789-0");
34       });
35     </script>
36   </div>
37     <div id="div-gpt-ad-123456789-1">
38     <script>
39       googletag.cmd.push(function() {
40          googletag.display("div-gpt-ad-123456789-1");
41       });
42     </script>
43   </div>
44 </body>
45 </html>
 

Example of a synchronous Google Publisher Tag

Here is a sample of the full code for creating a synchronous Google Publisher Tag, illustrating many of the common features and syntax in a synchronous GPT ad request.

We recommend not enabling synchronous requests, because they can delay the loading of a page's content. We recommend using asynchronous tags instead. Learn more about asynchronous tags and cases where it's still appropriate to use synchronous tags.
For users on slow connections, such as 2G, external scripts dynamically injected using document.write() can delay the display of main page content for tens of seconds. This is another reason why we recommend using asynchronous tags instead of synchronous rendering. Learn more about issues with 2G and document.write()
1 <html>
  • Lines 3-4 is boiler-plate that synchronously 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 synchronously. You don't need to edit this section of code.

  • (Optional) Lines 5-7 set page-level attributes for ad slots that serve AdSense. Changing these attributes overrides overrides any styles set in DFP or AdSense. This is not commonly used since you can set this in DFP. The developer documentation for the .set() function describes how to set AdSense parameters in GPT.

  • Lines 9 and 12: "/1234/travel/asia" specifies the network code (1234) and targeted ad unit (travel/asia). Find your network code in the "Admin" tab of DFP.

    [728, 90] sets the creative size eligible to serve to this ad slot. Indicate multiple sizes using the syntax: [[width1, height1], [width2, height2], [width3, height3]]. Associate all sizes here with the targeted ad unit, allowing you to narrow the list down based on the specific slot. When using multiple size ad slots, declare the slot sizes in the same order that they appear in DFP. Learn more about slot definition and sequentiality.

    Lines 9, 12, 23, 25, 28, and 30: "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. Use the same <div> ID consistently for a given position on a page, as it is used for optimization in a wide range of areas.

    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 the same from page to page as long as there aren't multiple instances of the same div name on the same page.

    Learn more about the DFP inventory structure, ad unit hierarchy, and how ad units inherit targeting in the inventory overview.

  • Lines 11, 14, 15, and 16 (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"]). To target multiple keys, call the function multiple times, as in the second case: (gender=male and age=20-30).

    The developer documentation for the .setTargeting() function describes how to set key-value parameters in GPT. Learn more about setting targeting and sizes with GPT.

  • Line 16: googletag.pubads().setTargeting("topic","basketball"); sets page-level key-value targeting. When configuring targeting with page-level key-values, all ad slots inherit this targeting. Like slot-level key-values, you can associate multiple values with one key: ("key", ["value1", "value2", "value3"]).

  • Line 17: googletag.pubads().enableSingleRequest(); enables Single Request Architecture (SRA). Include this line to call all ad slots on the page in one call (allows for guaranteed roadblocks, and may have performance benefits for your page). Currently, SRA does not support Google Programmable Ads (GPA).

  • Line 18: To render 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 23: (Optional) style="width: 728px; height: 90px" is the size that the element takes before the creative is rendered. If using multi-size tags, we recommend either omitting this (in that case, the size of the element takes the size of the selected creative when rendered) or making both dimensions large enough to contain the largest eligible creative. For single size ad tags, use this parameter to expand the container element until the creative loads so that other page elements don't shift when the creative renders.

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

If you can't edit the header of your web pages

You can use GPT without modifying the header of your web pages.

Option 1: Use an inline tag to define where the ad unit appears on the page, rather than using the page header. With an inline tag, the entire GPT ad slot definition and request, including loading the GPT library, is contained within a single <script> tag. Here are examples of defining an ad slot inline.

Because the ad tag uses the GPT JavaScript library, you must include the code that loads the library before including the ad tag code (as shown in the following examples).

Inline asynchronous GPT example

These inline GPT examples do not support SRA.

Call the GPT JavaScript library

<script async="async" src="https://www.googletagservices.com/tag/js/gpt.js"></script>
<script>
 var googletag = googletag || {};
 googletag.cmd = googletag.cmd || [];
</script>

Sample ad tag 1: Asynchronous inline tag

<div id="div-gpt-ad-1234567891234-0">
  <script>
    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 (does not support ad-slot level targeting)

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

These inline GPT examples do not support SRA.

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

<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 (does not support ad slot-level targeting)

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

Option 2: Use conventional GPT implementation, but put the ad slot definitions in the body of your HTML, rather than the header. The code that loads the library and defines the ad slots must be called before you request ads for those slots. Because the code isn't segmented into the head and body of your page and you must manage its sequence, this approach is more complex, but provides the flexibility of SRA.

Use a non-JavaScript GPT tag to create a 1x1 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 line item with a size of 1x1 and add a transparent pixel image creative to it.

  3. Target the 1x1 line item to the ad unit created in step 1.

  4. Create a non-JavaScript GPT tag calling the impression pixel and specifying the ad unit created in step 1. For example:

    <img src='http://pubads.g.doubleclick.net/gampad/ad?iu=/1234/ad_unit&sz=1x1&t=&c=12345678'/>

    Learn how to generate non-JavaScript based URLs

  5. Use the impression pixel tag in one of two ways:

    • Add the tag to a custom 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.

Was this article helpful?
How can we improve it?