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.:
window['FB'];
or
name = 'FB';
foo = window[name];
So to check:
if (typeof window[name] === "undefined")
...except that doesn't differentiate between the property not existing at all, or existing but having the value undefined.
or
if (name in window)
...but that checks the prototype as well as the object. It's fine for window, though.
window.hasOwnProperty(name)does not work ifname == 'twttr.widgets'.
Right, you have to break it up:
var index = 0,
parts = name.split('.'), // doesn't handle [] notation
result;
result = window;
index = 0;
try {
while (typeof result !== "undefined" && result !== null && index < parts.length) {
result = result[parts[index++]];
}
}
catch (e) {
}
if (index < parts.length) {
// Didn't find all of it
}
...or something to that effect.
I've always just used things like:
if (window[name]) {
return 'it exists';
} else {
return 'nope';
}
EDIT: This works because if window[name] isn't there, the if determines undefined to be false.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With