Check out "Do you speak JavaScript?" - my latest video course on advanced JavaScript.
Language APIs, Popular Concepts, Design Patterns, Advanced Techniques In the Browser

AI driven open source library for measuring your web page carbon footprint

AI driven open source library for measuring your web page carbon footprint Photo by Chris LeBoutillier

Some people say that 2023 will be the year of AI. With tools like ChatGPT and DALL·E the world is definitely changing. There are different opinions on how such instruments will affect the everyday tasks of the professionals. My two cents (for now) are that those are just tools to achieve what we want quicker and more efficiently. Who knows, someday I may call myself a "prompt engineer". For the time being, though, I'm still writing a lot of stuff alone and occasionally ask ChatGPT for help.

Backstory

So, what is this article all about? Friday evening, reading Twitter, the weekend is approaching, and I'm wondering if I have to work on a small project. You know, hacking something quickly for fun. I had no ideas, so I decided to ask, guess who - ChatGPT:

Challenge accepted! A good friend of mine (and colleague) Lorenzo Pieri did an interesting talk some time ago called "Greta is not happy with your website, and she’s right.". I never thought about my job from that angle, and I'm finding the idea of measuring the carbon footprint interesting. He even assembled the website envirotechnical.eu, where we can find materials on that same topic.

Implementation

The idea is in place, and I decided to continue using ChatGPT. The first and very significant "problem" is the library's name. Well, eco.js is taken so:

Nice but eco.js is taken. Give me another catchy name.
"GreenWeb.js" - a library that helps developers create more eco-friendly and energy-efficient web applications.
Nice. Can you give me other name suggestions for that library. So far we have eco.js which is taken and greenweb.js which I like. Something else which is also catchy?
Sure, here are a few shorter suggestions for a library that helps developers create more eco-friendly and energy-efficient web applications:

Eco.js, EcoJS, EcoLib, EcoOpt, EcoEff.
Actually all of those are taken. Don't add ".js" at the end. Give me more suggestions for such library. Library that will measure the carbon footprint of a web page based on memory. Come up with a name based on the words "carbon", "emissions", "measure". The name of this library may be something that doesn't exists and should be short one.
CarboMeasure, CarboScope, EmissionMeter, EcoMem, GreenMem, MemEmissions, CarboCheck

Boom! It will be Carboscope. Job done 😀. Now we have a name; let's see how to write this library. I did a quick research, and it is not simple. There are companies specializing in such types of measurement, and implementing something accurate for just one weekend is not achievable. But again, let's ask the bot:

That works. Ok, but how to make such library. I mean how to measure the energy consumption of a javascript app (web page)?
Measuring the energy consumption of a JavaScript application can be a complex task, as it depends on many factors, such as the user's device, the browser, and the specific code that is running. However, here are a few methods that could be used to estimate the energy consumption of a web page:

- Browser APIs: Some browser APIs such as the Battery Status API and the Navigation Timing API can provide information about the device's battery level and the time it takes to load and render a page, which can be used to estimate the energy consumption.
- Instrumentation: One could instrument the JavaScript code running on a page to measure the time and resources used by specific functions or operations.
- Machine Learning: One could use machine learning to predict the energy consumption of a web page by training a model with data collected from a set of different devices and browsers, and then using that model to estimate the energy consumption of new pages.
- Real Device Testing: One could measure the energy consumption of a web page using a device that is capable of measuring the power consumption of the device.

Keep in mind that creating such a library would require a deep understanding of the web platform, JavaScript and performance optimization, as well as machine learning.

I tried using the battery API, but that's only giving me the percentage to the second number after the dot. So, I'm not sure I can make meaningful conclusions based on that. I like the second point.

I'm interested in point 2. Give me more about that.
Instrumentation is a method of measuring the performance of a web page by adding code to the page that measures specific operations or functions. Here are a few examples of how instrumentation could be used to estimate the energy consumption of a web page:

- Timers: You could use JavaScript's built-in performance.now() function to measure the time it takes to execute specific functions or operations. This information can be used to estimate the energy consumption based on the time and resources used by the operation.
- Profiling: You could use JavaScript's built-in console.profile() and console.profileEnd() functions to measure the time and resources used by specific functions or operations. This information can be used to estimate the energy consumption.
- Memory usage: You could use JavaScript's built-in memory management functions such as performance.memory to measure the amount of memory that is being used by the page and its resources.

Ok, ok, I get it. It's complicated. But in that last answer, something is interesting. The third point talks about performance.memory. I decided to see what's this about, and it looks like I can get the heap size of the currently running JavaScript. I could correlate this to a formula where I used the memory usage against the consumed energy.

Sadly, performance.memory is deprecated. So, that's a dead end.

Since performance.memory is now depricated what else I can use to see the memory usage of a web page?
You can use the Performance.memory property to check the memory usage of a web page, it is now deprecated and removed from most of the browser, but you can use the following methods to check the memory usage of a web page:

- performance.memory : It is supported in some older version of browser, but it's not recommended to use it.
- performance.getEntries(): It returns an array of performance entries that have been recorded by the browser.
- performance.measure(): You can use this method to measure the performance of a specific section of code.

A-ha ... performance.getEntries() is what I'm going to use. That's not deprecated. According to MDN there is a transferSize property that represents the size (in octets) of the fetched resource. This may not include the memory used by JavaScript, but it contains the downloaded files.

A couple of minutes later and I had this:

function _getMemory() {
  if (typeof performance !== 'undefined' && performance.getEntries) {
    let size = performance.getEntries().reduce(
      (total, entry) => total + entry.transferSize || 0,
      0
    );
    return size / (1024 * 1024); // in MB
  } else {
    console.warn('Performance API is not supported');
    return 0;
  }
};

This function tells me how many MBs the current page consumed (kind of). Now I need the formula to calculate the carbon footprint.

Give me formula for calculating a carbon footprint based on memory usage?
Calculating a carbon footprint based on memory usage can be complex, as it depends on a variety of factors, such as the specific memory technology being used, the energy source used to power the memory, and the energy efficiency of the memory system. However, here is a general formula that could be used to estimate the carbon footprint of a web page based on its memory usage:

Carbon Footprint (kg CO2e) = Memory Usage (MB) * Emission Factor (kg CO2e/MB) ...
Give me example of using the formula?
Here is an example of how the formula could be used to estimate the carbon footprint of a web page based on its memory usage:

Let's say a web page has a memory usage of 150 megabytes.
The emission factor for electricity generated by coal is 0.5 kg CO2e/MB.
The carbon footprint of the web page would be:

Carbon Footprint (kg CO2e) = 150 (MB) * 0.5 (kg CO2e/MB) = 75 kg CO2e

Fast forward to Sunday when I'm writing this article. I used the formula above and published a 660B library called Carboscope.

The library

Carboscope is basically a short JavaScript snippet. Get the code from here, paste it into the console of any page, and run CarboScope.measure(). You'll start getting messages about the carbon footprint. For example:

🌿 CarboScope: 5.23 kg CO2e
🌿 CarboScope: 5.41 kg CO2e
🌿 CarboScope: 8.22 kg CO2e

The library is also distributed as an npm package if you need, for some reason, to get the footprint as a number.

// npm install carboscope and then:

import CarboScope from 'carboscope';

CarboScope.asNumber();

Conclusion

It was fun 🤓. ChatGPT proved to be a valuable asset during my brainstorming session. Not only did it provide insightful information on various topics, but it also effectively guided me towards a solution for my problem. While it's important to note that the suggested solutions may not always be the most optimal, I was still impressed with its usefulness and capabilities.

If you enjoy this post, share it on Twitter, Facebook or LinkedIn.