页面加载问题后将脚本标签附加到头部

问题描述

我正在尝试在页面完全加载后将 Google AdSense 脚本附加到 head 标记。简而言之,这里是触发错误代码

var tag = document.createElement("script");
tag.src = "https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js";
tag.data-ad-client="ca-pub-xxxxxxx"; //error gets triggered here
tag.defer="defer";
document.getElementsByTagName("head")[0].appendChild(tag);

在控制台中我得到

Uncaught SyntaxError: Invalid left-hand side in assignment

并引用这一行

tag.data-ad-client="ca-pub-xxxxxxx";

如何解决这个问题,如果我能让它以这种方式工作,广告会正常显示吗?

解决方法

试试这样写

tag['data-ad-client'] = "ca-pub-xxxxxxx";
,

尝试使用括号表示法代替.. 方括号表示法允许使用不能与点表示法一起使用的字符,这里就是这种情况,因为 data-ad-client 包含字符 '-'

var tag = document.createElement("script");
tag.src = "https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js";
tag['data-ad-client']="ca-pub-xxxxxxx"; //error gets triggered here
tag.defer="defer";
document.getElementsByTagName("head")[0].appendChild(tag);

,

使用tag.setAttribute('data-ad-client') = 'ca-pub-xxxxxx';

或者datasettag.dataset.adClient = 'ca-pub-xxxx';

,

给你,但我的建议是使用 Async 而不是 defer

    <script>
    var tag = document.createElement("script");
    tag.src = "https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js";
    tag.setAttribute('data-ad-client','ca-pub-xxxxxxx');
    tag.defer=true;
    document.getElementsByTagName("head")[0].appendChild(tag);
    </script>

新的广告代码略有变化

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1234567890123456" crossorigin="anonymous"</script> 

你可以试试这个答案 New Adsense Code