我想使用 Google DFP(Google 发布商代码),但它不起作用。
我定义了保存
googletag
的全局变量:
googletag: any = window.googletag || {};
将脚本添加到页面:
addGPTScript() {
// Ad gtp.js script in the page
const gads = document.createElement('script');
gads.async = true;
gads.type = 'text/javascript';
const useSSL = 'https:' === document.location.protocol;
gads.src = (useSSL ? 'https:' : 'http:') + '//www.googletagservices.com/tag/js/gpt.js';
const node = document.getElementsByTagName('script')[0];
node.parentNode.insertBefore(gads, node);
if (this.googletag.apiReady) {
console.log(this.googletag)
}
console.log(this.googletag)
}
ngOnInit(): void {
this.addGPTScript();
}
但是第一个处于状态的 console.log 从未加载,第二个则打印
undefined
。我检查了 HTML HEAD 标签,发现脚本已添加。
我注意到以下代码不起作用:
// Ad gtp.js script in the page
const gads = document.createElement('script');
gads.async = true;
gads.type = 'text/javascript';
const useSSL = 'https:' === document.location.protocol;
gads.src = (useSSL ? 'https:' : 'http:') + '//www.googletagservices.com/tag/js/gpt.js';
const node = document.getElementsByTagName('script')[0];
node.parentNode.insertBefore(gads, node);
我删除了上面的内容并添加到 HTML Head 标签中:
<script type="text/javascript" async src="https://www.googletagservices.com/tag/js/gpt.js"></script>
您是否尝试在 gpt.js 加载完成后进行输出? 声明 gads 之后直接将其放入行中:
gads.onload = setTimeout(function() {
console.log(window.googletag)
}, 10);
您的日志记录应该在将脚本附加到 DOM 后立即完成。然后它不会被加载,它会在执行你的函数和调用 console.log 之后异步加载。