자주 발생하는 구현 실수 방지하기

다음 시나리오는 GPT를 구현했습니다. 이러한 구현은 현재 사용할 경우 앞으로 계속 지원된다는 보장은 없습니다. 대부분의 극단적인 경우 이러한 구현은 광고 게재가 예상치 못한 방식으로 중단될 수 있습니다. 이는 지원되지 않는 구현으로 간주됩니다.

각 시나리오에는 표시된 문제를 해결하기 위한 추천 방법이 포함되어 있습니다.

이 목록은 잠재적인 문제의 완전한 목록을 나타내지 않습니다. 해결해야 할 문제 유형을 파악하는 데 해결해야 합니다

또한 구현에 따라 사이트 내에서 이러한 변경이 필요할 수 있습니다.

흔히 발생하는 실수

시나리오 1: GPT 자바스크립트 라이브러리의 비공식 사본 사용

대략적인 사용 사례 설명 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 API를 호출할 준비가 되었다고 가정합니다. 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는 불리언 플래그를 빠르면 googletag.apiReady로 신뢰할 수 있는 어설션을 만들 수 있도록 API를 호출할 준비가 되었습니다.

시나리오 4: 난독화된 코드 구문 사용

대략적인 사용 사례 설명 최소화된 GPT 라이브러리 코드의 정확한 구문을 사용하고 있다면 문제가 발생할 수 있습니다 API는 계속 변경되므로 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의 일반적인 타이밍을 준수하여 경합 상태를 피하세요. 유효한 예시 부분 주문에는 다음이 포함됩니다. <ph type="x-smartling-placeholder">
    </ph>
  • 정의-사용-디스플레이 <ph type="x-smartling-placeholder">
      </ph>
    1. 페이지 수준 설정 정의
    2. 슬롯 정의
    3. enableServices()
    4. 디스플레이 슬롯
  • 디스플레이 사용 설정 <ph type="x-smartling-placeholder">
      </ph>
    1. 페이지 수준 설정 정의
    2. enableServices()
    3. 슬롯 정의
    4. 디스플레이 슬롯

시나리오 7: 클로저 및 자바스크립트 변수 범위 지정 오용

대략적인 사용 사례 설명 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가 명령 대기열의 콜백이 즉시 실행되거나 실행되지 않을 수 있습니다. 이전 이렇게 하면 큐에 추가된 명령어의 동작이 변경됩니다.

문제를 방지하려면 코드를 다음과 같이 작성해야 합니다. 실행되기 때문에 주의가 필요합니다. 를 참조하세요.

시나리오 8: 디스플레이를 호출한 후 DOM 내에서 슬롯 컨테이너 이동

대략적인 사용 사례 설명 디스플레이를 호출한 후 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");