// 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);
由于在加载 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();
}
// 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();
}
// 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 || [];
// 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]);
}
}
)
调用 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");
// 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);
}
[[["易于理解","easyToUnderstand","thumb-up"],["解决了我的问题","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["没有我需要的信息","missingTheInformationINeed","thumb-down"],["太复杂/步骤太多","tooComplicatedTooManySteps","thumb-down"],["内容需要更新","outOfDate","thumb-down"],["翻译问题","translationIssue","thumb-down"],["示例/代码问题","samplesCodeIssue","thumb-down"],["其他","otherDown","thumb-down"]],["最后更新时间 (UTC):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"]]