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 來引用圖像。
添加回答
舉報