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?
First off, you don’t need that
eval(you almost never do), you can index into a JavaScript object using a string and bracketed notation, e.g.:or
So to check:
…except that doesn’t differentiate between the property not existing at all, or existing but having the value
undefined.or
…but that checks the prototype as well as the object. It’s fine for
window, though.Right, you have to break it up:
…or something to that effect.