[英]Javascript checking whether a variable is undefined
To check whether adsense script is loaded or not, I use this: 要检查是否已加载adsense脚本,请使用以下命令:
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.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. 是的,请首先检查
typeof adsbygoogle
的typeof adsbygoogle
,如果加载了全局变量adsbygoogle
,则将返回此adsbygoogle
。
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. 使用
typeof
检查全局变量将永远不会由于尝试访问未定义的变量而产生任何异常。 Reference: JavaScript check if variable exists (is defined/initialized) 参考: JavaScript检查变量是否存在(已定义/初始化)
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. 只需在第一步中检查对象是否存在,然后再加载它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.