简体   繁体   English

用xhr2 / blob预加载图像

[英]Preload image with xhr2/blob

I want to preload a image with xhr2/blob, because I need a download progress, so I don't want to using new Image() for the preloading, But I not sure the xhr2/blob can it store the cache before next requrest, anynoe know the details? 我想用xhr2 / blob预加载图像,因为我需要下载进度,所以我不想使用new Image()进行预加载,但是我不确定xhr2 / blob是否可以在下一次请求之前存储缓存,谁知道细节吗? can I using xhr2/blob for preloading? 可以使用xhr2 / blob进行预加载吗? Or it only can use new Image()? 还是只能使用新的Image()?

Yes xhr will use the cached version if there is one. 是的,如果有xhr,它将使用缓存的版本。

You can check in the Network panel of your dev tools, or just compare the loading time of these requests : 您可以在开发工具的“网络”面板中签入,或者只是比较这些请求的加载时间:

 const url = 'https://dl.dropboxusercontent.com/s/4e90e48s5vtmfbd/aaa.png?' + Math.random(); // the same for both requests, but different for each snippets function requestData(cb){ let xhr = new XMLHttpRequest(), startTime; xhr.open('get', url); xhr.onload = e => { console.log(performance.now() - startTime); if(cb){ cb(); } } startTime = performance.now(); xhr.send(); } requestData(requestData); 


No you can not use it to preload your images. 不,您不能使用它来预加载图像。

Every image loading is asynchronous, even if served from http cache, or blobURI, or dataURI * 即使从http缓存,blobURI或dataURI提供服务,每个图像加载也是异步的*

 fetch('https://dl.dropboxusercontent.com/s/4e90e48s5vtmfbd/aaa.png') .then(resp => resp.blob()) .then(blob => { let url = URL.createObjectURL(blob); for(let i=0; i<5; i++){ let img = new Image(); img.src = url; console.log('synchronous', img.naturalWidth, img.complete); } let img = new Image(); img.onload = e => console.log('async', img.naturalWidth, img.complete); img.src = url; }); 

*(At least it should be, some UAs are known to load the resources in a synchronous way if served from cache) *(至少应该如此,如果从缓存中提供服务,则已知某些UA以同步方式加载资源)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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