net - UK (2020-04)

(Antfer) #1

The CSS Zen Garden demonstrates the separation
of style and structure: hundreds of different
designs are applied to the same markup
(http://www.csszengarden.com/)


FEATURE


DETECTION
I reckon that about 90 per cent of the DOM
scripting I’ve done has come down to some
combination of querySelector (‘find stuff’)
and addEventListener (‘do stuff to it’). Even
though there’s universal support for both
of those methods in modern browsers,
there’s still no harm in doing a bit of
feature detection before using them:
if (document.querySelector &&
document.addEventListener) {
// Your DOM scripting code goes here.
}

Or, if you don’t like having all your code
indented within curly braces like that,
you can use feature detection to tell
older browsers when to bail. If either
querySelector or addEventListener aren’t
supported, use a return statement to exit:
if (!document.querySelector ||
!document.addEventListener) {
return;
}
// Your DOM scripting code goes here.

The same goes for any other JavaScript
APIs you use in your code: geolocation,
notifications, the Cache API, local storage,
fetch... you can use feature detection to
ensure that older browsers won’t choke on
your code.
Interestingly, even though feature
detection isn’t really necessary in CSS
(because CSS simply ignores what it
doesn’t understand), you can now use
feature queries in CSS in order to test for
browser support:
@supports (display: grid) {
// Your grid code goes here
}

Ah but what about older browsers that
don’t understand @supports? Well,
because of the error-handling model of
CSS, those browsers will ignore everything
inside the curly braces... which is exactly
what you want them to do!
Free download pdf