I want to test whether the CustomEvent
constructor is supported.
var ev;
if (/* CustomEvent constructor supported? */) {
ev = new CustomEvent('splat');
} else {
ev = document.createEvent('Event');
ev.initEvent('splat');
}
this.dispatchEvent(ev);
I don't have any machines running IE nearby to test it. Does it throw an error so I can use try/catch, or do I need to do something else? What about older non-IE browsers?
The following should work, even on IE6, i've tested it on an old XP machine with IE6.
if (typeof CustomEvent === 'function') {
ev = new CustomEvent('splat');
}
Yeah, try/catch should work, ie8 will throw:
TypeError: 'CustomEvent' is undefined
Whereas ie11 will throw:
Object doesn't support this action
Other older browsers will either have not implemented it at all, or not as a constructor, so should result in similar errors
so you could do something like:
var isSupported = (function() {
try {
new CustomEvent('test');
return true;
} catch (e) {
return 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