Posted to Blog on January 2, 2021

Clever conditional loading of JavaScript

Recently, I came across a number of articles talking about using a technique that checks against a set of variables from a user’s device to then either load or not load assets like JavaScript.

I’ve previously talked about the prefers-reduced-data media query, which once supported in browsers, will be a great tool to use in both JavaScript and CSS. But there is another technique to reduce data and loading of assets that we can use right now. This technique involves using the navigator object to check whether a user’s device matches your criteria in order to load that asset.

For example, here we check if the user’s device has enough RAM. If they do, we load up the JavaScript, if not, we don’t.

if (navigator.deviceMemory > 1) {
    await import('./costly-module.js');

This technique can work well to detect a whole range of information, from internet connection to the user’s preferences.

A great article from Umar Hansa explains further, with a number of examples. Have a read of JavaScript: Conditional JavaScript, only download when it is appropriate to do so.

Is it supported?

Support is dependant on the module you are looking to detect. The example above using deviceMemory is supported in Chromium-based browsers. Which nowadays covers around 70% of global usage according to caniuse.

Is it only useful for Javascript?

Not at all. This technique could also be used to reduce down heavy animations to be lighter on the user’s device, or perhaps reduce/remove the loading of certain images, or image file types. You could in theory even change the entire stylesheet for a less data-heavy design, with no custom fonts for example. There is a lot of potential for this technique.

References: Umar Hansa

Find this resource useful?

We hope so. We want everyone to be able to benefit from articles like this one. That is why we need your help.

Our resources take time to research and write. The site is run by ourselves and sometimes volunteer contributors in our spare time. Please consider supporting our efforts.

Plant a tree in our forest or Buy us a coffee