JavaScript可以获取当前页面消耗的总流量吗?

作者站长头像
站长
· 阅读数 17

如题,可以在前端做到统计页面消耗的字节数吗?

回复
1个回答
avatar
test
2024-07-11

performance.getEntriesByType('resource') 用找个可以获取到页面上所有加载的资源,然后计算他们的 encodedBodySize

const size = Array.from(performance.getEntriesByType('resource')).reduce((a,b)=>a+b.encodedBodySize,0)

console.log(size)

performance.getEntriesByType('navigation')encodedBodySize 可以获取到页面的大小。

结合一下

const size = performance.getEntries().filter(v=>['resource','navigation','frame'].includes(v.entryType)).reduce((a,b)=>a+b.encodedBodySize,0)/1024

console.log(size)

不过刚刚测试了一下,好像不是很准 😂,跟浏览器的 Network 显示有些差异。

回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容