避免常見導入錯誤
下列情境代表了您在
導入 GPT雖然這類實作方式目前看來可與現行 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 會在 API 可供呼叫時填入布林旗標 googletag.apiReady,讓您能做出可靠的斷言。 |
情境 4:依賴經過模糊處理的程式碼語法
一般應用情況說明 |
如果您依賴精簡版 GPT 程式庫程式碼的確切語法,幾乎肯定會發生中斷情形。我們持續不斷變更,因此請限制您僅能使用 API 參考指南中所述的 API 用途
GPT 內部運作方式的持續改進
例如,常見的要求是偵測
呼叫 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 的一般時間安排,以免發生競爭狀況。有效的部分排序範例包括:
-
Define-Enable-Display
- 定義頁面層級設定
- 定義時段
- 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:在呼叫顯示作業後,在 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 修補、polyfilling) 瀏覽器 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); }
|
除非另有註明,否則本頁面中的內容是採用創用 CC 姓名標示 4.0 授權,程式碼範例則為阿帕契 2.0 授權。詳情請參閱《Google Developers 網站政策》。Java 是 Oracle 和/或其關聯企業的註冊商標。
上次更新時間:2024-10-14 (世界標準時間)。
[null,null,["上次更新時間:2024-10-14 (世界標準時間)。"],[[["Avoid unofficial copies of GPT JavaScript libraries, always access them from an official Google domain."],["Utilize `googletag.cmd.push` to queue functions and ensure they execute when GPT is ready, rather than relying on script tag listeners or checking the `googletag` object directly."],["Strictly adhere to the documented GPT API and refrain from relying on obfuscated code or overwriting any GPT functions or variables to prevent breakages."],["Maintain the correct order of GPT calls, like defining page-level settings and slots before enabling services and displaying ads, to avoid race conditions."],["Be mindful of JavaScript variable scoping and closures, especially when using `googletag.cmd.push`, to prevent unexpected behavior due to delayed execution."],["Ensure slot containers are positioned correctly in the DOM before calling `display` to avoid reflows and unpredictable rendering."],["Refrain from overwriting browser APIs, as it can negatively impact the functionality of third-party scripts like GPT."]]],["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"]]