避免常见的植入错误
    
    
      
    
    
      
      使用集合让一切井井有条
    
    
      
      根据您的偏好保存内容并对其进行分类。
    
  
  
      
    
  
  
  
  
  
    
  
  
    
    
    
    
      以下场景代表了在实现 GPT 时最常见的一些错误。尽管此类实现似乎能很好地适应当前的
      版本,我们无法保证它们以后还会继续如此。在
      在大多数极端情况下,这些植入方式都可能会导致广告投放以不可预知的方式中断。
      这类广告被视为不受支持的实现方式。
    
    
      每种场景都包含针对所示问题的建议解决方法。
    
    
      请注意,此列表并未详尽列出所有可能存在的问题,但应该能帮助您确定可能需要解决的问题类型。
    
    
      此外,您可能需要在网站中查找可能需要进行此类更改的所有位置,具体取决于您的实现方式。
    
    常见错误
    场景 1:使用 GPT JavaScript 库的非官方副本
    
      
        | 应用场景概要说明 | 在您自己的服务器上托管 gpt.js、pubads_impl.js 或其加载的任何库,或者从非官方来源加载这些文件。 | 
      
        | 包含错误的代码段示例 | // Incorrect: Accessing these files from an unofficial source
<script async src="https://www.example.com/tag/js/gpt.js"></script> | 
      
        | 建议的错误修正方法 | // Correct: Access these files from a Google domain
<script src="https://securepubads.g.doubleclick.net/tag/js/gpt.js" crossorigin="anonymous" async></script>
// Also correct, if using Limited Ads
<script src="https://pagead2.googlesyndication.com/tag/js/gpt.js" async></script> | 
    
    场景 2:依赖于 gpt.js 脚本代码监听器
    
      
        | 宽泛应用场景说明 | 假设 GPT API 已经准备就绪,可以在 JavaScript 文件 gpt.js加载的是错误,因为 API 的某些部分由pubads_impl.js文件。因此,通过任何方式(包括框架)从附加到脚本代码的事件监听器中依赖 API 是不正确的。 | 
      
        | 存在错误的代码段示例 | var tag = document.createElement('script');
tag.type = 'text/javascript';
tag.src = (useSSL ? 'https:' : 'http:') +
        '//www.googletagservices.com/tag/js/gpt.js';
// Incorrect: Attaching a callback to the script's onload event.
tag.onload = callback;
var node = document.getElementsByTagName('script')[0];
node.parentNode.insertBefore(tag, node); | 
      
        | 建议的错误修正方法 | // Make sure that googletag.cmd exists.
window.googletag = window.googletag || {};
googletag.cmd = googletag.cmd || [];
// Correct: Queueing the callback on the command queue.
googletag.cmd.push(callback); | 
      
        | 问题修复的说明 / 说明 | googletag.cmd中保存了一个命令,这些命令会在 GPT 后立即运行
          准备就绪。这是确保在 GPT 加载后运行回调的正确方法。 | 
    
    场景 3:检查 googletag 对象以了解 GPT 是否准备就绪
    
      
        | 应用场景概要说明 | 由于在加载 JavaScript 文件 gpt.js或定义googletag对象时,GPT API 可能尚未准备就绪,因此检查该对象以确定 GPT API 是否可用并不可靠。 | 
      
        | 包含错误的代码段示例 | // Incorrect: Relying on the presence of the googletag object
// as a check for the GPT API.
if (typeof googletag != 'undefined') {
 functionProcessingGPT();
} | 
      
        | 建议的错误修正方法 | // Correct: Relying on googletag.apiReady as a check for the GPT API.
if (window.googletag && googletag.apiReady) {
 functionProcessingGPT();
} | 
      
        | 修复程序的说明/描述 | GPT 将填充该布尔标记
          googletag.apiReady
          此 API 已可供调用,以便您进行可靠的断言。 | 
    
    场景 4:依赖于经过混淆处理的代码语法
    
      
        | 应用场景概要说明 | 如果您要依赖经过缩减的 GPT 库代码的精确语法,那么几乎可以
          那么肯定会遇到中断问题我们正不断改进“API”,因此请仅选择 API 参考指南中载述的 API。
          GPT 的内部运作机制,以实现持续改进。 例如,常见的要求是检测 PubAdsService 何时
          以便调用
 refresh()。 | 
      
        | 包含错误的代码段示例 | // Incorrect: Relying on an obfuscated property.
if (googletag.pubads().a != null) {
 functionProcessingGPT();
} | 
      
        | 建议的错误修正方法 | // Correct: Relying on public GPT API methods
// (i.e. googletag.pubadsReady in this case).
if(window.googletag && googletag.pubadsReady) {
 functionProcessingGPT();
} | 
      
        | 问题修复的说明 / 说明 | 只能依赖公共 API。如果要检测 PubAdsService 是否
          我们有一个布尔值
          googletag.pubadsReady。 | 
    
    场景 5:覆盖 GPT 中的任何函数或变量
    
      
        | 应用场景概要说明 | 需要覆盖 GPT 使用的任何函数或变量的用例可能会随时中断
          因为这不是受支持的用例GPT 内部构件中的时间变化可能会导致此问题
          这是由破坏造成的错误行为 | 
      
        | 包含错误的代码段示例 | // Incorrect: Haphazardly overwriting a googletag.* property.
googletag.cmd = []; | 
      
        | 修正错误的建议方法 | // Correct: Never overwrite googletag.* properties if they already exist.
// Always check before assigning to them.
googletag.cmd = googletag.cmd || []; | 
    
    场景 6:按错误顺序调用 GPT
    
      
        | 应用场景概要说明 | 随着 GPT 内部结构的演变,竞态条件可能会导致故障。不正确的
          因执行特定时间而正常运行的一组有序语句
          未来可能无法继续正常运行。 | 
      
        | 存在错误的代码段示例 | // Incorrect: Setting page-level key-value targeting after calling
// googletag.enableServices().
googletag.enableServices();
googletag.defineSlot(...);
googletag.pubads().setTargeting(e, a); | 
      
        | 建议的错误修正方法 | // Correct: Setting page-level key-value targeting before calling
// googletag.enableServices().
googletag.pubads().setTargeting(e, a);
googletag.defineSlot(...);
googletag.enableServices(); | 
      
        | 修复程序的说明/描述 | 请务必遵循 GPT 的常规时间安排,以避免出现竞态条件。示例有效
          部分排序包括:
          <ph type="x-smartling-placeholder"> </ph>
            
              定义-启用-显示
              
                定义页面级设置定义槽enableServices()显示槽
              Enable-Define-Display
              
                定义页面级设置enableServices()定义槽显示槽 | 
    
    场景 7:滥用闭包和 JavaScript 变量作用域
    
      
        | 应用场景概要说明 | 对 JavaScript 变量作用域以及传递给 googletag.cmd.push的函数中捕获的变量的值做出了错误的假设。 | 
      
        | 存在错误的代码段示例 | // Incorrect: Variable x is declared outside the anonymous function
// but referenced within it.
for (var x = 0; x < slotCount; x++) {
 window.googletag.cmd.push(
  function(){
    // If GPT is not yet loaded, this code will be executed subsequently when
    // the command queue is processed. Every queued function will use the last value
    // assigned to x (most likely slotCount).
    // This is because the function closure captures the reference to x,
    // not the current value of x.
    window.googletag.display(slot[x]);
  })
 }
} | 
      
        | 建议的错误修正方法 | window.googletag.cmd.push(
 function(){
  // Correct: We both declare and reference x inside the context of the function.
  for (var x = 0; x < slotCount; x++){
   window.googletag.display(slot[x]);
  }
 }
) | 
      
        | 修复程序的说明/描述 | 
            在 JavaScript 中,闭包通过引用而非值来捕获变量。这意味着
            如果某个变量被重新赋值,那么当函数运行函数时,
            会稍后执行。因此,闭包中代码的行为可能会因回调是立即执行还是延迟执行而有所变化。
           
            如果是异步加载的 GPT,则取决于 GPT 加载
            回调可能会立即执行,也可能不会。在上一个
            这将改变已排队的命令的行为。
           
            为避免任何问题,编写代码时不应假设函数
            会立即执行,因此应谨慎处理
            JavaScript 作用域规则的概念
           | 
    
    场景 8:调用 display 后在 DOM 内移动槽容器
    
      
        | 宽泛应用场景说明 | 调用 display 之后在 DOM 中移动或插入槽容器会导致
          GPT 中出现意外的重排和意外行为。 | 
      
        | 存在错误的代码段示例 | // Incorrect: Moving slot containers after calling display
googletag.defineSlot("/1234/travel/asia", [728, 90], "div-gpt-ad-123456789-0");
googletag.enableServices();
googletag.display("div-gpt-ad-123456789-0");
...
// Inserting another element before the slot container, pushing the slot container down the page.
document.body.insertBefore(someOtherElement, document.getElementById("div-gpt-ad-123456789-0")); | 
      
        | 建议的错误修正方法 | // Correct: Make any DOM order changes before calling display
document.body.insertBefore(someOtherElement, document.getElementById("div-gpt-ad-123456789-0"));
...
googletag.defineSlot("/1234/travel/asia", [728, 90], "div-gpt-ad-123456789-0");
googletag.enableServices();
googletag.display("div-gpt-ad-123456789-0"); | 
    
    场景 9:覆盖浏览器 API
    
      
        | 宽泛应用场景说明 | GPT 不支持覆盖(即 monkey 修补、polyfill)浏览器 API。
          这种做法有可能会以意想不到的方式破坏 GPT 等第三方脚本。 | 
      
        | 包含错误的代码段示例 | // Incorrect: Overwriting window.fetch
const { fetch: originalFetch } = window;
window.fetch = (...args) => {
 console.log('Fetching!');
 return originalFetch(resource, config);
}; | 
      
        | 建议的错误修正方法 | // Correct: Avoid making changes to browser APIs.
// If you need custom logic, consider leaving the browser API intact.
const myFetch = (...args) => {
  console.log('Fetching!');
  return window.fetch(...args);
} | 
    
  
  
  
  
    
  
 
    
  
  
    
    
      
       
    
    
  
  
  如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
  最后更新时间 (UTC):2025-07-25。
  
  
  
    
      [null,null,["最后更新时间 (UTC):2025-07-25。"],[],["The content outlines unsupported methods of implementing GPT (Google Publisher Tag) that may cause unpredictable ad serving issues. Key actions to avoid include: using unofficial GPT JavaScript libraries, relying on script tag listeners or the `googletag` object to determine API readiness, using obfuscated code syntax, overwriting GPT functions/variables, mis-ordering GPT calls, and misusing JavaScript variable scoping. Correct implementations involve using Google-hosted libraries, leveraging `googletag.cmd.push`, respecting API timing, and modifying the DOM before calling display. Also, avoid overwriting browser APIs.\n"]]