Reload ads without a page refresh

You can use the refresh functionality of an asynchronous Google Publisher Tag to dynamically reload ads without having to refresh the entire contents of your page.

The refresh functionality only works in asynchronous mode. Calling the refresh() function will request a new ad with an updated correlator value. Learn more the correlator value and Cache-busting with GPT.

To comply with Google policy and enable your inventory to compete on Ad Exchange, you must declare which portions of your inventory refresh.

In order to implement this functionality, you'll need to generate an asynchronous GPT tag and apply some modifications. The sample implementation shown below will request a new ad from the ad server every 30 seconds. The part of the code you'll need to modify is highlighted.

Sample implementation
<html>
<head>
<script>var googletag = window.googletag || {cmd: []};</script>
<script async src="//www.googletagservices.com/tag/js/gpt.js"></script>
<script>
googletag.cmd.push(function() {
  var REFRESH_KEY = 'refresh';
  var REFRESH_VALUE = 'true';
  // This slot is allowed to refresh, as it contains the targeting keys which have
  // been declared for refresh.
  googletag.defineSlot('1234/sports', [300, 600], 'div-1').
    setTargeting(REFRESH_KEY, REFRESH_VALUE).
    addService(googletag.pubads());
  // Number of seconds to wait after the slot becomes viewable.
  var SECONDS_TO_WAIT_AFTER_VIEWABILITY = 60;

  googletag.pubads().addEventListener('impressionViewable', function(event) {
    var slot = event.slot;
    if (slot.getTargeting(REFRESH_KEY).indexOf(REFRESH_VALUE) > -1) {
      setTimeout(function() {
        googletag.pubads().refresh([slot]);
      }, SECONDS_TO_WAIT_AFTER_VIEWABILITY * 1000);
    }
  });

  googletag.enableServices();
});
</script>
</head>
<body>

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

</body>
</html>

Manually testing the refresh() function

To manually test the refresh() function, you can temporarily add a refresh button to your web page by pasting the following code snippet immediately before the </body> tag. When you click the button, all ad slots on the page are refreshed but the page itself is not.

<form onsubmit="googletag.pubads().refresh();return false;">
  <input type="submit" value="refresh" />
</form>
 

Learn more about the way the refresh function works with GPT in the Google Publisher Tag API reference guide. To see another example, see the "Refreshing specific ad slots" section in the Advanced GPT samples.

Was this article helpful?
How can we improve it?