1 回答

TA贡献1784条经验 获得超2个赞
#1:您可以通过如下请求 获取Content-Length资源的标头:HEAD
fetch('https://your-domain/your-resource', { method: 'HEAD' })
.then(r => console.log('size:', r.headers.get('Content-Length'), 'bytes'));
这样只下载标题,仅此而已。
#2:或者,您可以使用Resource Timing API:
const res = performance.getEntriesByName('https://your-domain/your-resource');
console.log(res[0].transferSize, res[0].encodedBodySize, res[0].decodedBodySize);
请注意,资源需要位于同一子域中,否则您将必须添加Timing-Allow-OriginCORS 标头。
#3:另一种选择是将图像下载为 blob:
fetch('https://your-domain/your-resource')
.then(r => r.blob())
.then(b => console.log(b.size, URL.createObjectURL(b)));
如果在初始加载后调用,这当然会重新下载图像,但如果最初使用此方法加载图像,则可以使用对象 URL 来引用图像。
添加回答
举报