0

To check whether adsense script is loaded or not, I use this:

var isAdsenseNotLoaded = (typeof adsbygoogle.loaded === 'undefined');

But from many users has this error in stack trace:

ReferenceError: adsbygoogle is not defined
    at http://example.com/file.js:1:42020

So should I also check whether adsbygoogle and also adsbygoogle.loaded ?

trante
  • 33,518
  • 47
  • 192
  • 272

3 Answers3

11

You need to check if adsbygoogle is defined first:

var isAdsenseNotLoaded = !adsbygoogle || typeof adsbygoogle.loaded === 'undefined';

Patsy Issa
  • 11,113
  • 4
  • 55
  • 74
  • I suppose first part will be `adsbygoogle == false` or similar thing ? Because I need to check whether adsense is not loaded. – trante Aug 06 '15 at 16:50
  • @trante updated, missed the Not in `isAdsenseNotLoaded` – Patsy Issa Aug 07 '15 at 09:31
  • This does not work. when adsbygoogle is undefined it doesn't do anything. I tried alert(isAdsenseNotLoaded); only works when the object is defined. – dryleaf Jul 20 '18 at 04:15
1

Yes, check for typeof adsbygoogle first, this will return if the global variable adsbygoogle is loaded.

var isAdsenseNotLoaded = (typeof adsbygoogle === 'undefined' || typeof adsbygoogle.loaded === 'undefined');

Checking for global variables with typeof will never produce any exceptions due to trying to access an undefined variable. Reference: JavaScript check if variable exists (is defined/initialized)

Community
  • 1
  • 1
Liglo App
  • 3,719
  • 4
  • 30
  • 54
  • This does not work. when adsbygoogle is undefined it doesn't do anything. I tried alert(isAdsenseNotLoaded); only works when the object is defined. – dryleaf Jul 20 '18 at 04:15
0

So the whole object is not defined

var isAdsenseNotLoaded = (typeof adsbygoogle === 'undefined' || typeof adsbygoogle.loaded === 'undefined');

Just check in the first step if the object exists and then if it is loaded.

Wa Kai
  • 466
  • 5
  • 12
  • This does not work. when adsbygoogle is undefined it doesn't do anything. I tried alert(isAdsenseNotLoaded); only works when the object is defined. – dryleaf Jul 20 '18 at 04:14