adsense - Javascript checking whether a variable is undefined - Stack Overflow

To check whether adsense script is loaded or not, I use this:var isAdsenseNotLoaded = (typeof adsbygoog

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 ?

Share Improve this question edited Aug 7, 2015 at 6:56 trante asked Aug 6, 2015 at 12:37 trantetrante 34k49 gold badges196 silver badges275 bronze badges 3
  • 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
Add a ment  | 

4 Answers 4

Reset to default 11

You 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({})

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742356924a4428622.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信