简体   繁体   中英

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

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:

在此处输入图像描述

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!

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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM