Conditional JavaScript – JavaScript

Umar has written this great tutorial on how to use some browser API’s to check the capabilities of the device and network, and then use that to load additional (expensive) JavaScript (and as a result probably more expensive/heavy interactions).

Let’s take a look at some of the use cases.

Device Memory

You can retrieve the device memory by adding a meta tag to your HTML and the server will respond with the memory of the current device as a header. This is a NON JavaScript approach and could allow you to serve certain resources from the server itself. Maybe you’ve got a really complicated animation using Canvas and WebGL, potentially send something else down the pipe instead.


The number of CPU on the device can be used to measure the number of threads that can be run at once, giving you some insight into the capabilities of the current device.

The example Umar gives here is when using Workers as part of the Web Workers API.

Battery Level

I remember when the battery level was used for nefarious reasons by companies like Uber, where they would raise the cost of the fare if they determined that their customer was about to run out of phone batter (and assumably be stranded without a way home).

My assumption that it was shut off completely is wrong, it turns out that Chromium browsers still allow for this to be used (which is like 74% of the population, so worth using where you can).

If you are going to be using this, I’d recommend using it as a IF the battery is okay then load the additional resources, rather than IF the battery is bad then don’t load the resources. This means that even on browsers that don’t support the API the users will still be a battery boosting performance.

More and more…

Those are just a few of the tips that Umar has provided. You also get insight into how to use

  • Network connection
  • Device Storage
  • Save Data

We’ve all been there. Low battery 🔋️, no charger, and you start clearing apps in the hope that your 4% lasts on the journey home.

A page with JavaScript will utilise more battery than a page without JavaScript – and yes, the same applies to CSS and images.

The Network Download, Parse and Execution costs will defintely use battery, but don’t forget the variety of tasks which JavaScript is capable of e.g. creating long-running timers.

An excerpt from Conditional JavaScript – JavaScript

View original article

Subscribe to our Newsletter

Add your email address and receive an email every Friday covering off everything worth knowing about building your websites responsively.