I am having this issue. I have a script that checks if variable exists, because some scripts load asyncronously, like FB for Facebook or twttr for Twitter.
function whenAvailable(name, callback, interval) {
interval || (interval = 100); // ms
window.setTimeout(function() {
if ((window.hasOwnProperty && window.hasOwnProperty(name)) || window[name] || !!eval(name)) {
return callback();
} else {
window.setTimeout(arguments.callee, interval);
}
}, interval);
}
Looks like this
if ((window.hasOwnProperty && window.hasOwnProperty(name)) || window[name] || !!eval(name))
does not work. IE throws error for eval(name) -- e.g. if name = 'FB', it says it can't eval 'FB' which is undefined.
window.hasOwnProperty(name) does not work if name == 'twttr.widgets'.
Is there a universal and cross browser check for existence of var by var name?
twttr.widgets. There can be a variable namedtwttrwhich may have a propertywidgets, but hopefully you can see it's not as simple as "does this property exist"windowcalledtwttr.widgets. It would be unusual, but it's perfectly legal.window['twittr.widgets'] = "foo";.