简体   繁体   中英

Javascript checking whether a variable is undefined

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 ?

您需要检查是否adsbygoogle定义adsbygoogle

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM