避免常見導入錯誤
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
下列情境代表了您在
導入 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 時,GPT API 可能還未準備就緒
或在定義 googletag 物件的情況下檢查該物件
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 的一般時間安排,以免發生競爭狀況。有效範例
部分排序包括:
-
定義啟用多媒體廣告
- 定義網頁層級設定
- 定義時段
- enableServices()
- 顯示版位
-
啟用定義多媒體廣告
- 定義網頁層級設定
- 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 中移動運算單元容器
應用實例概要說明 |
在呼叫顯示後,在 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 不支援覆寫 (又稱為猴子修補、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 和/或其關聯企業的註冊商標。
上次更新時間:2025-07-25 (世界標準時間)。
[null,null,["上次更新時間:2025-07-25 (世界標準時間)。"],[[["\u003cp\u003eAvoid unofficial copies of GPT JavaScript libraries, always access them from an official Google domain.\u003c/p\u003e\n"],["\u003cp\u003eUtilize \u003ccode\u003egoogletag.cmd.push\u003c/code\u003e to queue functions and ensure they execute when GPT is ready, rather than relying on script tag listeners or checking the \u003ccode\u003egoogletag\u003c/code\u003e object directly.\u003c/p\u003e\n"],["\u003cp\u003eStrictly adhere to the documented GPT API and refrain from relying on obfuscated code or overwriting any GPT functions or variables to prevent breakages.\u003c/p\u003e\n"],["\u003cp\u003eMaintain the correct order of GPT calls, like defining page-level settings and slots before enabling services and displaying ads, to avoid race conditions.\u003c/p\u003e\n"],["\u003cp\u003eBe mindful of JavaScript variable scoping and closures, especially when using \u003ccode\u003egoogletag.cmd.push\u003c/code\u003e, to prevent unexpected behavior due to delayed execution.\u003c/p\u003e\n"],["\u003cp\u003eEnsure slot containers are positioned correctly in the DOM before calling \u003ccode\u003edisplay\u003c/code\u003e to avoid reflows and unpredictable rendering.\u003c/p\u003e\n"],["\u003cp\u003eRefrain from overwriting browser APIs, as it can negatively impact the functionality of third-party scripts like GPT.\u003c/p\u003e\n"]]],["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"],null,[]]