Optimizing Performance - jellyfish-tom/TIL GitHub Wiki

[SOURCES] https://css-tricks.com/using-feature-detection-to-write-css-with-cross-browser-support/

User Agent Detection (browser sniffing)[BAD PRACTICE]

It is usually done as follows:

  • All browsers add a JavaScript property on the global window object called navigator and this object contains a userAgent string property.
  • If we are using Chrome, then the following should return true: (navigator.userAgent.indexOf("chrome") !== -1).
  • However, under the Internet Explorer section on MDN, we just get Internet Explorer. IE doesn’t put its name in the BrowserName/VersionNumber format. Luckily, Internet Explorer provides its own native detection in the form of Conditional Comments. This means that adding the following in our HTML should suffice:
<!--[if lt IE 9]>
  <style>
    input {
      display: block;
    }
  </style>
<![endif]-->

Unfortunately, over time, some critical flaws emerged in User Agent Detection. So much so that Internet Explorer stopped supporting Conditional Comments from version 10 onward.

Instead of User Agent Detection, we can check for feature support in browser.

Feature Detection

When we use feature detection, we are essentially doing the following:

🔎 Testing whether a browser is actually able to run a specific line (or lines) of HTML, CSS or JavaScript code.

💪 Taking a specific action based on the outcome of this test.

  • Feature detection is a technique, as opposed to a specific tool or technology. This means that there are various (equally valid) ways to accomplish feature detection.
  • Feature detection programmatically tests code. This means that browsers actually run a piece of code to see what happens, as opposed to merely using inference or comparing it against a theoretical reference/list as done with User Agent Detection.

CSS feature detection with @supports

The @supports rule allows CSS to be conditioned on implementation support for CSS properties and values. This rule makes it much easier for authors to use new CSS features and provide good fallback for implementations that do not support those features. This is particularly important for CSS features that provide new layout mechanisms, and for other cases where a set of related styles needs to be conditioned on property support.

ex.

@supports (::before) {
  input {
    display: none;
  }
}

Bare in mind that @supports have it s own support (dough) matrix (it may not be supported in all browsers).

Modernizr

You can also do CSS feature detection with Modernizr. External tool that does not rely on Browser API. It has its advantage (not relying on API), but also comes with a downside of using external tool in your project and additional overhead to do something most browsers support out of the box through @supports. Ask yourself if it makes sense, to load Modernizr into your project just to support 3% of users.

⚠️ **GitHub.com Fallback** ⚠️