JavaScript - 从 HTML img src 获取大小(以字节为单位)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28430115/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript - Get size in bytes from HTML img src
提问by Punit S
I would like to know how to get the size in bytes from the "src" from an "img" tag with HTML/JS.
我想知道如何从带有 HTML/JS 的“img”标签的“src”中获取以字节为单位的大小。
<img src="https://ofbuckleyandbeatles.files.wordpress.com/2011/01/testpattern.gif"/>
In the above example I would basicly want to know how big "testpattern.gif" is (in bytes).
在上面的例子中,我基本上想知道“testpattern.gif”有多大(以字节为单位)。
Thanks in advance.
提前致谢。
回答by Punit S
Well, this is 2017 and you can now use Resource Timing API to extract an image's transferSize, encodedBodySize, decodedBodySize within javascript:
好吧,这是 2017 年,您现在可以使用 Resource Timing API 在 javascript 中提取图像的 transferSize、encodedBodySize、decodedBodySize:
Below is the code to access size information for allthe imgs on a page (see the caveat to all below):
下面是访问页面上所有imgs大小信息的代码(请参阅以下所有警告):
var imgElems = document.getElementsByTagName('img');
for ( var i=0, len = imgElems.length; i < len; i++ )
{
var url = imgElems[i].src || imgElems[i].href;
if (url && url.length > 0)
{
var iTime = performance.getEntriesByName(url)[0];
console.log(iTime.transferSize); //or encodedBodySize, decodedBodySize
}
}
- Make sure you run the above code after document onload (to be sure images are loaded)
- Due to CORS, timing information for images coming from a different domain may not be available (unless the different domain's server has set Timing-Allow-Origin HTTP response header)
- Be sure resource timing api is available for the browser(s) you are targetting : http://caniuse.com/#feat=resource-timing
- Make sure you get a grasp of the difference between transferSize, encodedBodySize, decodedBodySize to be sure you use the right size attribute.
- 确保在文档加载后运行上述代码(以确保加载图像)
- 由于 CORS,来自不同域的图像的计时信息可能不可用(除非不同域的服务器设置了 Timing-Allow-Origin HTTP 响应标头)
- 确保资源计时 api 可用于您的目标浏览器:http: //caniuse.com/#feat=resource-timing
- 确保您掌握了 transferSize、encodedBodySize、decodedBodySize 之间的区别,以确保使用正确的 size 属性。

