Is there a way of storing a built-in javascript method in a variable to set different behaviour for when this method isn't available in certain browsers?
My specific case is for intersectionObserver which isn't available in Safari or older MS browsers. I have some animations triggered by this and would like to turn them off if intersectionObserver isn't available.
what I want to do essentially this:
var iO = intersectionObserver;
if ( !iO ) {
// set other defaults
}
I don't really want to load a polyfill or library for just one feature?
Many thanks
Emily
The in Operator is widely used to detect features supported by the browser. JavaScript features are globally available as a property to window
object. So we can check if window
element has the property.
if("IntersectionObserver" in window){
/* work with IntersectionObserver */
}
if("FileReader" in window){
/* work with FileReader */
}
The
in
operator returnstrue
if the specified property is in the specified object or its prototype chain.
Syntax: prop in object
[source: developer.mozilla.org]
So you can also save the result in a boolean
variable and use it later in your code.
var iO = "IntersectionObserver" in window; /* true if supported */
if ( !iO ) {
// set other defaults
}