0

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?

PHP User
  • 2,350
  • 6
  • 46
  • 87

4 Answers4

0

try writing it in this way

tag['data-ad-client'] = "ca-pub-xxxxxxx";
Dharman
  • 30,962
  • 25
  • 85
  • 135
Phani
  • 92
  • 7
0

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);
Ran Turner
  • 14,906
  • 5
  • 47
  • 53
0

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

Or alternatively dataset: tag.dataset.adClient = 'ca-pub-xxxx';.

Mikita Belahlazau
  • 15,326
  • 2
  • 38
  • 43
0

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

Niresh
  • 611
  • 5
  • 16