控制广告加载和刷新

在我们使用入门和基本概念示例中,Google 发布商代码 (GPT) 库的 display() 方法用于注册和显示广告位。不过,有时最好或甚至有必要拆分这些操作,以便更精确地控制何时加载广告内容。例如,使用意见征求管理平台或根据用户操作请求广告内容时。

在本指南中,我们将探讨 GPT 提供的机制,以控制广告内容的加载和按需提取新的广告内容。此示例的完整代码可以在基于事件的请求示例页面上找到。

控制广告加载

默认情况下,display() 方法的行为是注册、请求广告内容并将其呈现到广告位中。您可以通过 PubAdsService.disableInitialLoad() 方法停用自动请求和呈现广告内容。

停用初始加载后,调用 display() 将仅注册广告位。在用户采取第二项操作之前,系统不会加载任何广告内容。这样,您就可以精确控制何时发出广告请求。

为避免发出意外的广告请求,必须先调用 disableInitialLoad(),然后才能启用该服务,然后再调用 display()

<!doctype html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="description" content="Request GPT ads based on events." />
    <title>Event-based ad requests</title>
    <script async src="https://securepubads.g.doubleclick.net/tag/js/gpt.js"></script>
    <script>
      window.googletag = window.googletag || { cmd: [] };

      googletag.cmd.push(() => {
        // Define the ad slot.
        googletag
          .defineSlot("/6355419/Travel", [728, 90], "div-for-slot")
          .setTargeting("test", "event")
          .addService(googletag.pubads());

        // Disable initial load.
        // This prevents GPT from automatically fetching ads when display is called.
        googletag.pubads().disableInitialLoad();
        googletag.enableServices();
      });
    </script>
    <style></style>
  </head>
  <body>
    <div id="div-for-slot" style="width: 300px; height: 250px"></div>
    <script>
      googletag.cmd.push(() => {
        // Register the ad slot.
        // An ad will not be fetched until refresh is called.
        googletag.display("div-for-slot");

        // Register click event handler.
        document.getElementById("showAdButton").addEventListener("click", () => {
          googletag.cmd.push(() => {
            googletag.pubads().refresh();
          });
        });
      });
    </script>
  </body>
</html>

在此示例中,系统会停用初始加载,以确保在调用 display() 时不会发出广告请求,也不会呈现任何内容。槽已准备好接受并显示广告,但只有刷新槽后才能发出广告请求。

刷新

PubAdsService.refresh() 方法用于使用新的广告内容填充一个或多个广告位。此方法可用于尚未加载任何内容的槽(由于 disableInitialLoad()),或替换已填充的槽位的内容。但是,只有通过调用 display() 注册的槽才符合刷新条件。

<!doctype html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="description" content="Request GPT ads based on events." />
    <title>Event-based ad requests</title>
    <script async src="https://securepubads.g.doubleclick.net/tag/js/gpt.js"></script>
    <script>
      window.googletag = window.googletag || { cmd: [] };

      googletag.cmd.push(() => {
        // Define the ad slot.
        googletag
          .defineSlot("/6355419/Travel", [728, 90], "div-for-slot")
          .setTargeting("test", "event")
          .addService(googletag.pubads());

        // Disable initial load.
        // This prevents GPT from automatically fetching ads when display is called.
        googletag.pubads().disableInitialLoad();
        googletag.enableServices();
      });
    </script>
    <style></style>
  </head>
  <body>
    <div id="div-for-slot" style="width: 300px; height: 250px"></div>
    <button id="showAdButton">Show/Refresh Ad</button>
    <script>
      googletag.cmd.push(() => {
        // Register the ad slot.
        // An ad will not be fetched until refresh is called.
        googletag.display("div-for-slot");

        // Register click event handler.
        document.getElementById("showAdButton").addEventListener("click", () => {
          googletag.cmd.push(() => {
            googletag.pubads().refresh();
          });
        });
      });
    </script>
  </body>
</html>

在此修改后的示例中,当用户点击“显示/刷新广告”按钮时,系统会调用 refresh() 方法。这会触发请求:获取新的广告内容并将其加载到已注册的广告位,并覆盖任何现有的内容。

请注意,在上面的示例中,调用 refresh() 方法时不带参数,因此刷新所有注册的广告位。不过,您也可以通过向 refresh() 方法传递一组广告位来刷新特定广告位。有关示例,请参阅刷新广告位示例。

最佳实践

使用 refresh() 时,应遵循一些最佳做法。

  1. 请勿过快刷新。

    过快刷新广告位可能会导致广告请求受到限制。 为防止出现这种情况,请避免每 30 秒刷新一次槽。

  2. 请勿不必要地调用 clear()

    刷新广告位时,请先不要调用 PubAdsService.clear()。这没有必要,因为 refresh() 会替换指定广告位的内容,无论之前是否加载了任何广告内容。在调用 refresh() 之前立即调用 clear() 只会增加用户看到空白槽的时间。

  3. 仅刷新可见广告位

    使用 refresh() 替换从不可见的广告位的内容可能会大幅降低 ActiveView 率。ImpressionViewableEvent 可用于确定广告位何时变为可见,如以下示例所示。

    googletag.cmd.push(function() {
      var REFRESH_KEY = 'refresh';
      var REFRESH_VALUE = 'true';
    
      googletag.defineSlot('/6355419/Travel',[728, 90], 'div-for-slot')
          .setTargeting(REFRESH_KEY, REFRESH_VALUE)
          .setTargeting('test', 'event')
          .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();
    });