Search
Clear search
Close search
Google apps
Main menu

Advanced Google Publisher Tag samples

This article provides advanced samples of Google Publisher Tags for desktop and mobile implementations.

Learn more using the Google Publisher Tag API reference guide. You can also learn about basic GPT implementation from the Sample Google Publisher Tags article.

Please note that the samples shown use a test network, ad slot and targeting configurations. Your implementation will need to be customized for your network and configuration.

Implementing tags on pages with infinite contents

You can dynamically generate new ad content using GPT.

Category exclusions and roadblocks are only honored for ads served by the same SRA request. Including multiple SRA calls in a single page load may result in competitive ads being displayed on the same page.

A sample of the full code you would use to implement tags with infinite page contents is shown below. The sample features a button on the bottom of the page to dynamically generate new content.

Sample implementation
<html>
<head>
<title>Infinite Scroll Example</title>

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

<script>

var adslot0;

 googletag.cmd.push(function() {

   // Declare any slots initially present on the page
   adslot0 = googletag.defineSlot('/6355419/Travel', [728, 90], 'leaderboard').
       setTargeting("test","infinitescroll").
       addService(googletag.pubads());

   // Infinite scroll requires SRA
   googletag.pubads().enableSingleRequest();

   // Disable initial load, we will use refresh() to fetch ads.
   // Calling this function means that display() calls just
   // register the slot as ready, but do not fetch ads for it.
   googletag.pubads().disableInitialLoad();

   // Enable services
   googletag.enableServices();
 });

 // Function to generate unique names for slots
 var nextSlotId = 1;
 function generateNextSlotName() {
   var id = nextSlotId++;
   return 'adslot' + id;
 }

 // Function to add content to page, mimics real infinite scroll
 // but keeps it much simpler from a code perspective.
 function moreContent() {

   // Generate next slot name
   var slotName = generateNextSlotName();

   // Create a div for the slot
   var slotDiv = document.createElement('div');
   slotDiv.id = slotName; // Id must be the same as slotName
   document.body.appendChild(slotDiv);

   // Create and add fake content 1
   var h1=document.createElement("H2")
   var text1=document.createTextNode("Dynamic Fake Content 1");
   h1.appendChild(text1);
   document.body.appendChild(h1);

   // Create and add fake content 2
   var h2=document.createElement("H2")
   var text2=document.createTextNode("Dynamic Fake Content 2");
   h2.appendChild(text2);
   document.body.appendChild(h2);

   // Define the slot itself, call display() to 
   // register the div and refresh() to fetch ad.
   googletag.cmd.push(function() {
     var slot = googletag.defineSlot('/6355419/Travel', [728, 90], slotName).
         setTargeting("test","infinitescroll").
         addService(googletag.pubads());

     // Display has to be called before
     // refresh and after the slot div is in the page.
     googletag.display(slotName);
     googletag.pubads().refresh([slot]);
   });
 }
</script>

<style>
 body > div {
	margin-bottom: 1em;
	border: solid 1px black;
	width: 728px
 }
 body > img {
	margin-bottom: 1em;
	display: block
 }
 body > button {
	position: fixed;
	bottom: 10px;
 }
</style>
</head>

<body>
 <h1>GPT Test Page - Infinite Scroll</h1>

 <!-- First fake content -->
 <text>
 <h2> Initial Fake Content </h2>
 </text>

 <!-- First ad -->
 <div id="leaderboard"> 
     <script>
        // Call display() to register the slot as ready
        // and refresh() to fetch an ad.
        googletag.cmd.push(function() {
          googletag.display('leaderboard');
          googletag.pubads().refresh([adslot0]);
        });
     </script> 
 </div>

 <!-- More initial fake content -->
 <text>
  <h2> Initial Fake Content 1 </h2>
  <h2> Initial Fake Content 2 </h2>
 </text>

 <!-- Button to load more content dynamically. -->
 <button onclick="moreContent()">More Content</button>

</body>
</html>

Refreshing specific ad slots

You can refresh a specified array of ad slots using asynchronous mode in GPT. A sample of the full code you would use to implement this functionality is shown below. The sample features two ad slots and corresponding buttons to refresh the slots with new ads.

Sample implementation
<html>
<head>
<title>GPT Training - Slot Refresh</title>

<script> 

 // Load GPT asynchronously
 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>

<script>

 // GPT slots
 var gptAdSlots = [];

 googletag.cmd.push(function() {

  // Define the first slot
  gptAdSlots[0] = googletag.defineSlot('/6355419/Travel',[728, 90],'leaderboard0').
      setTargeting('test', 'refresh').
      addService(googletag.pubads());

  // Define the second slot
  gptAdSlots[1] = googletag.defineSlot('/6355419/Travel',[728, 90],'leaderboard1').
      setTargeting('test', 'refresh').
      addService(googletag.pubads());

  // Configure SRA
  googletag.pubads().enableSingleRequest();

  // Start ad fetching
  googletag.enableServices();
 });

 // Button action which refreshes the first slot
 var refreshFirstSlot = function() {
   googletag.cmd.push(function() {
     googletag.pubads().refresh([gptAdSlots[0]]);
   });
 };

 // Button action which refreshes the second slot
 var refreshSecondSlot = function() {
   googletag.cmd.push(function() {
     googletag.pubads().refresh([gptAdSlots[1]]);
   });
 };

 // Button action which refreshes both slots
 var refreshBothSlots = function() {
   googletag.cmd.push(function() {
     googletag.pubads().refresh([gptAdSlots[0], gptAdSlots[1]]);
   });
 };

 // Button action which clears all slots
 var clearAllSlots = function() {
   googletag.cmd.push(function() {
     googletag.pubads().clear();
   });
 };
</script>
</head>

<body>
 <div>
  <h1>GPT Training - Slot Refresh</h1>
  <div id='leaderboard0' style="width:728px;height:90px;"> 
     <script>
          googletag.cmd.push(function() {
            googletag.display('leaderboard0');
          });
     </script> 
  </div>

  <div id='leaderboard1' style="width:728px;height:90px;"> 
     <script>
          googletag.cmd.push(function() {
            googletag.display('leaderboard1');
          });
     </script> 
  </div>
 </div>

 <div> 
  <!-- Refresh the first slot -->
  <button onclick="refreshFirstSlot();">Refresh Top Ad</button>

  <!-- Refresh the second slot -->
  <button onclick="refreshSecondSlot();">Refresh Bottom Ad</button>

  <!-- Refresh both slots -->
  <button onclick="refreshBothSlots();">Refresh Both Ads</button>

  <!-- Clear slots -->
  <button onclick="clearAllSlots();">Clear Ads</button>
 </div>

</body>
</html>

Learn more about Reloading ads without refreshing the page.

Implementing tags for responsive design

You can tag your page for responsive design using GPT. A sample of the full code you would use to implement responsive design is shown below. To test the responsive functionality in the sample, resize your window and refresh the page.

GPT responsive ads in this sample do not dynamically resize on change of the browser size. You can add your own custom code to refresh the ad slots on resize.

Sample implementation
<html>
<head>
<title>GPT Training - Responsive Test Page</title>
<script async src="https://www.googletagservices.com/tag/js/gpt.js"></script>
<script>
    var googletag = googletag || {};
    googletag.cmd = googletag.cmd || [];
</script>
<script>

 // GPT slots
 var gptAdSlots = [];
 googletag.cmd.push(function() {

   // Define a size mapping object. The first parameter to addSize is
   // a viewport size, while the second is a list of allowed ad sizes.
   var mapping = googletag.sizeMapping().

   // Small ad
   addSize([100, 100], [88, 31]). 

   // Accepts both common mobile banner formats
   addSize([320, 400], [[320, 50], [300, 50]]). 
		
   // Same width as mapping above, more available height
   addSize([320, 700], [300, 250]).

   // Landscape tablet 
   addSize([750, 200], [728, 90]). 

   // Desktop
   addSize([1050, 200], [1024, 120]).build();

   // Define the GPT slot
   gptAdSlots[0] = googletag.defineSlot('/6355419/travel', [320, 50], 'ad-slot').
       defineSizeMapping(mapping).
       addService(googletag.pubads());
   googletag.pubads().setTargeting("test","responsive");

   // Start ad fetching
   googletag.enableServices();
 });
</script>
</head>

<body>
<h1>GPT Training - Responsive Test Page</h1>

<div id="ad-slot"> 
   <script>
     googletag.cmd.push(function() {
       googletag.display('ad-slot');
     });
   </script> 
</div>

<p><span>GPT responsive ads do not resize on change in the size of the browser.
  You can add your own custom code to refresh the ad slots on resize.
  To demonstrate responsive capabilities, re-size your window and refresh the page.</span></p>

</body>
</html>

Learn more about Building responsive ads.

Implementing tags for native ads with a fluid size

GPT can be configured to display a native ad with the custom "fluid" size. In this case, the ad slot will have the width of its parent container, and resize its height to fit the native creative content. A sample of the full code you would use to implement this functionality is shown below.

Sample implementation
<html>
<head>
<title>GPT Training - Native ads and fluid size</title>
<script>
 // Load GPT asynchronously
 var googletag = googletag || {};
 googletag.cmd = googletag.cmd || [];
 (function() {
   var gads = document.createElement('script');
   gads.async = true;
   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>
<script>

 // GPT slots
 var gptAdSlots = [];
 googletag.cmd.push(function() {


   // Define the GPT slot
   gptAdSlots[0] = googletag.defineSlot('/6355419/travel', 'fluid', 'ad-slot').
       addService(googletag.pubads());

   // Start ad fetching
   googletag.enableServices();
 });
</script>
</head>

<body>
<h1>GPT Training - Native Test Page</h1>

<div id="ad-slot" style=”width:600px;”> 
   <script>
     googletag.cmd.push(function() {
       googletag.display('ad-slot');
     });
   </script> 
</div>

</body>
</html>

If you're adding the "fluid" size to an existing Google Publisher Tag, ensure that 'fluid' is added as a requested size. For example:

.addSize([640, 480], 'fluid')

Learn more about native ads.

Implementing tags for lazy loading

You can tag your page for lazy loading (serving ads only when necessary) using Google Publisher Tags. For example, you may want to serve an ad toward the bottom of a page only when a user scrolls down to that portion of the page. A sample of the full code you would use to implement lazy loading is shown below.

Sample implementation
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Lazy loading in GPT</title>

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

    <script>
      var topSlot, bottomSlot; +       googletag.cmd.push(function() {
        topSlot = googletag.defineSlot('/6075/gpttraining', [300, 250], 'topAd').addService(googletag.pubads());
        bottomSlot = googletag.defineSlot('/6075/gpttraining', [728, 90], 'bottomAd').addService(googletag.pubads());
        googletag.pubads().disableInitialLoad();
        googletag.enableServices();
      });
    </script>
  </head>
  <body>
    <h1>Lazy loading in GPT</h1>

    <div id="topAd" style="width: 300px; height: 250px">
      <script>
        // Load the top ad as soon as possible. No lazy loading required here.
        googletag.cmd.push(function() {
          googletag.display('topAd');
          googletag.pubads().refresh();
        });
      </script>
    </div>

    <!-- Large div to make the bottom ad go below the fold. -->
    <div id="veryLongDiv" style="width: 200px; height: 1000px">intentionally left blank</div>

    <div id="bottomAd" style="width: 728px; height: 90px">
      <script>
        googletag.cmd.push(function() {
          // This will only register the slot. Ad will be fetched only 
          // when refresh is called.
          googletag.display('bottomAd');
        });
      </script>
    </div>

    <script>
      // Refresh the bottom slot when it is about to come into view.
      var refreshed = false;

      // Value of scrollY at which the ad is about to come into view.
      var adAlmostVisibleScrollValue = 300;

      // Warning: This is a sample implementation. Listening to onscroll without 
      // any throttling might not be very efficient.
      var listener = function() {
        if (window.scrollY >= adAlmostVisibleScrollValue && !refreshed) {
          googletag.cmd.push(function() {
            googletag.pubads().refresh([bottomSlot]);
          });
          // Refresh the ad only once.
          refreshed = true;

          // Remove the listener now.
          window.removeEventListener('scroll', listener);
        }
      }
      window.addEventListener('scroll', listener);
    </script>
    <br/>
      </body>
</html>

Control SafeFrame Container behavior through GPT

GPT provides fine-grained control of the SafeFrame container through the setSafeFrameConfig method. This method takes a JSON object as input and allows you to configure certain behaviors of SafeFrame containers created by GPT.

This method only impacts the behavior of ads rendered in a SafeFrame. It doesn't control whether an ad is rendered in a SafeFrame, which is determined by the creative type and SafeFrame settings in DFP.

You can also use the setForceSafeFrame parameter in the GPT API to force ads in a specific slot to always render in a SafeFrame.

The setSafeFrameConfig method returns a boolean value indicating whether the configuration settings were successfully parsed.

Details of the configuration object

The configuration object takes as an input a simple JSON object that is a map of keys and values (valid values described below).

Any other keys are ignored. If any values apart from true/false are found, the config is rejected and an error results.

Key name Description Valid values
allowOverlayExpansion Creatives can expand using the Overlay mode in the SafeFrame API. The expanded creative covers content on the rest of the page. true
false
allowPushExpansion Creatives can expand using the Push mode in the SafeFrame API. The expanded creative pushes down the content on the rest of the page. true
false
sandbox Instantiates the SafeFrame container with the sandbox attribute set to prevent top-level navigation.
 
Only works in browsers that support the new HTML5 sandbox attribute on iframes.

Setting this key blocks ads using plugins such as Flash, and may break ads or landing pages in certain browsers, especially on desktop. We recommend testing it by setting up an ad with a landing page running the plugin, then clicking through to the landing page to see if plugins are blocked.
true
Sample implementation
Example Description
googletag.pubads().setSafeFrameConfig({sandbox: true}); All ads on the page rendered inside SafeFrames use the sandbox attribute.
slot1=googletag.defineSlot('/123/sports', [468, 80], 'ad');
slot1.setSafeFrameConfig({sandbox:true});
Only slot1 is rendered inside the sandboxed SafeFrame. Affects no other ad slots.
slot1=googletag.defineSlot('/123/sports', [468, 80], 'ad');
slot1.setSafeFrameConfig({allowOverlayExpansion: false});
Ads rendered in SafeFrames in slot1 aren't allowed to perform overlay expansion.
slot1=googletag.defineSlot('/123/sports', [468, 80], 'ad');
slot1.setSafeFrameConfig({allowOverlayExpansion: false, sandbox:true});
Ads rendered in SafeFrames in slot1 aren't allowed to perform overlay expansion. Also sets the sandbox attribute.
slot1=googletag.defineSlot('/123/sports', [468, 80], 'ad');
slot1.setSafeFrameConfig({allowPushExpansion: false, sandbox:true});
Ads rendered in SafeFrames in slot1 aren't allowed to perform push expansion.

Learn more about rendering creatives using SafeFrame.

Was this article helpful?
How can we improve it?