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 .js:1:42020
So should I also check whether adsbygoogle
and also adsbygoogle.loaded
?
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./file.js:1:42020
So should I also check whether adsbygoogle
and also adsbygoogle.loaded
?
- Duplicate of this? – Paolo Gibellini Commented Aug 6, 2015 at 12:38
- 1 @Paolo Not quite - tha'ts adressing a single variable, rather than a nested property – James Thorpe Commented Aug 6, 2015 at 12:39
- The operation should be applied to all the interested elements. See the answers – Paolo Gibellini Commented Aug 6, 2015 at 12:42
4 Answers
Reset to default 11You need to check if adsbygoogle
is defined first:
var isAdsenseNotLoaded = !adsbygoogle || typeof adsbygoogle.loaded === 'undefined';
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)
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.
I'm going to guess that many people e here because they searched for OP's error message.
Putting window.
in front of adsbygoogle
solves the issue, because this way, if adsbygoogle
doesn't exist yet, it will be created.
(window.adsbygoogle = window.adsbygoogle || []).push({})