最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览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 .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({})
发布评论

评论列表(0)

  1. 暂无评论