I'm trying to append Google AdSense script to the head tag after page gets fully loaded. In brief here's the code that triggers the error
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);
In the console I get
Uncaught SyntaxError: Invalid left-hand side in assignment
and refers to this line
tag.data-ad-client="ca-pub-xxxxxxx";
How to fix this and if I could make it work this way, will ads appear normally?
try writing it in this way
tag['data-ad-client'] = "ca-pub-xxxxxxx";
Try using the bracket notation instead.. Square bracket notation allows the use of characters that can't be used with dot notation which is the case here since data-ad-client includes the character '-'
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);
Use tag.setAttribute('data-ad-client') = 'ca-pub-xxxxxx';
.
Or alternatively dataset : tag.dataset.adClient = 'ca-pub-xxxx';
.
Here you go, but my advice is to use Async instead of 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>
The new adcode has changed a bit
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1234567890123456" crossorigin="anonymous"</script>
You could try this answer New Adsense Code
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.