Getting Device RAM Information with Javascript

javascript
Published on May 7, 2019

Web applications are getting bigger and heavier each day. But such applications can only work properly if there is enough RAM on the device. It makes no sense to run a "memory-intensive" application if the current device has only 512MB of RAM.

It would be best if the application could present a "lite" version for devices with low memory and a normal version for devices that have a good enough RAM. With cloud technologies scaling the server's memory size on demand has become possible.

Taking such cases in mind, browsers have now included an API to give the amount of device memory. navigator.deviceMemory is a property that returns an approximate amount of the device RAM.

let ram = navigator.deviceMemory
  • Returned value is in gigabytes
  • The exact memory size of is not returned. The RAM value is rounded to the nearest value of 2, and then divided by 1024.
    For example 512MB will be returned as 0.5 and 1000MB will be returned as 1.
  • Upper and lower bounds are applied on the amount of RAM. The lower bound is 0.25 (representing 256MB or less) and upper bound is 8 (representing 8GB or more). So values will never be less then 0.25 and never greater than 8. This is done to ensure privacy of users.
    The possible range of values returned can be : 0.25, 0.5, 1, 2, 4 & 8.

Demo

The memory size of the current device is :

Sending Device Memory Information to the Server with Device-Memory HTTP Header

You don't need to use Javascript to send device memory information to your server. Rather you can just include a <meta> tag, and the browser will automatically send a Device-Memory HTTP header with every request it makes to the server.

<meta http-equiv="Accept-CH" content="Device-Memory">

On the server side you can read the value of this HTTP header and make decisions accordingly.

With Node :

const http = require('http');

const server = http.createServer((request, response) => {
    if('device-memory' in request.headers) {
        let ram = request.headers['device-memory'];

        // logic depending on the memory size of the request
    }
});

server.listen(3000);

With PHP :

if(isset($_SERVER['DEVICE-MEMORY'])) {
    $ram = $_SERVER['DEVICE-MEMORY'];
}

Browser Compatibility

navigator.deviceMemory is supported in Chrome & Edge.

In this Tutorial