Home > Enterprise >  How to calculate total transfer size of a page in javascript?
How to calculate total transfer size of a page in javascript?

Time:06-21

I'm trying to calculate the total transfer size of a webpage, as it is shown in the Network tab of the browser dev tools:

enter image description here

In order to achieve that, I'm trying to use the window.performance API. However, I get different values from what the browser says.

Here is my script to calculate the total transfer size:

  const getTransferSize = () => {
    let totalTransferSize = 0;

    performance.getEntriesByType('resource').map((resource) => {
      const data = resource.toJSON();
      totalTransferSize  = data.transferSize;
    });

    return totalTransferSize;
  };

  console.log(`${bytesSent / 1024 / 1024} MB`); // This returns 1.5MB instead of 2.7MB

Any idea why I'm not getting the full transfer size?

Would there be another way to calculate this? Maybe server-side using nodejs?

Thanks!

CodePudding user response:

Javascript doesn't have full access to network traffic. Hence, your script could not catch all the requests. It only catches the javascript-related resources. You may find your solution on nodejs side. Here is a related post for nodejs. node.js calculating bandwidth usage by domain

CodePudding user response:

Ok so actually I found that the browser extensions where included in the transfer size of the network tab. So for anyone wondering the same, simply open the website in private navigation to get more accurate results!

  • Related