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

pjk_ok
  • 618
  • 7
  • 35
  • 90
  • 1
    `if("IntersectionObserver" in window)`? `var iO = window.IntersectionObserver;`? – Sebastian Simon Feb 14 '18 at 19:00
  • That doesn't work - it also throws an error in my code editor @Xufox ? – pjk_ok Feb 14 '18 at 19:38
  • What does? Which error? – Sebastian Simon Feb 14 '18 at 19:47
  • 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. – pjk_ok Feb 15 '18 at 02:49
  • I haven't marked up the question marks as code, so they do not belong in the code. – Sebastian Simon Feb 15 '18 at 11:28

1 Answers1

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
}
Munim Munna
  • 17,178
  • 6
  • 29
  • 58
  • Thanks Munim. I can't believe someone down-voted the question. Feel free to upvote it if you want. – pjk_ok Mar 12 '18 at 16:57
  • 1
    This is how the [official w3c polyfill](https://github.com/w3c/IntersectionObserver/blob/7382ce7e834c57ea166081484bd8f8a6de84de04/polyfill/intersection-observer.js#L16) detects it as well – FellowMD Mar 18 '18 at 19:36