実装に関する一般的な誤りの回避
コレクションでコンテンツを整理
必要に応じて、コンテンツの保存と分類を行います。
次のシナリオは、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 スクリプトタグ リスナーに依存している
ユースケースの概要 |
JavaScript ファイル gpt.js が読み込まれたときに GPT API を呼び出す準備ができていると想定するのは誤りです。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 ライブラリ コードの正確な構文に依存している場合は、ほぼ確実に破損が発生します。Google は、GPT の内部動作を絶えず改善するために、GPT の内部動作を絶えず変更しています。使用は、API リファレンス ガイドに記載されている API に限定してください。
たとえば、refresh() を呼び出すために PubAdsService が完全に読み込まれたタイミングを検出することが一般的な要件です。
|
エラーのあるコード スニペットの例 |
// 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
<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 でスロット コンテナを移動または挿入すると、
望ましくないリフローや予測不能な動作が発生する場合もあります。
|
エラーのあるコード スニペットの例 |
// 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 では、ブラウザ 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 Developers サイトのポリシーをご覧ください。Java は Oracle および関連会社の登録商標です。
最終更新日 2025-07-25 UTC。
[null,null,["最終更新日 2025-07-25 UTC。"],[[["\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,[]]