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



What to read next

More from our resources, blogs and case studies

Find this resource useful?

I hope so. I want everyone to be able to benefit from articles like this one. That is why I'm kindly asking for your support.

These resources take time to research and write. The site is run by one person, with occasional volunteer contributors in spare time. Please consider supporting the project if you can.

Plant a tree with Ecologi or Donate £3