Create Feature detection for One Javascript Feature (intersectionObserver)
Asked Answered
B

1

11

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

Bullpup answered 14/2, 2018 at 18:5 Comment(5)
if("IntersectionObserver" in window)? var iO = window.IntersectionObserver;?Roaster
That doesn't work - it also throws an error in my code editor @Xufox ?Bullpup
What does? Which error?Roaster
That line of code. I tried using that to create the variable, but it underlines it as an error in my editor and won't process the code? Also i've never seen an if statement combined with two question marks before. Am i supposed to include the question marks? Unless that's shorthand for something I'm meant to know? I'm really confused.Bullpup
I haven't marked up the question marks as code, so they do not belong in the code.Roaster
D
18

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 returns true 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
}
Dumfound answered 10/3, 2018 at 2:40 Comment(2)
Thanks Munim. I can't believe someone down-voted the question. Feel free to upvote it if you want.Bullpup
This is how the official w3c polyfill detects it as wellArchaeozoic

© 2022 - 2024 — McMap. All rights reserved.