【问题标题】:Preload / cache images with URLs responding HTTP-redirects使用响应 HTTP 重定向的 URL 预加载/缓存图像
【发布时间】:2018-10-14 00:50:40
【问题描述】:

我想让浏览器预加载/缓存图像,以便更快地加载。通常这样做如下:

var URL = "http://example.com/image.jpg";
var image = new Image();
image.src = URL;

但在我的例子中,URL 响应的 HTTP 重定向大致如下所示:

$ curl -i "http://example.com/image.jpg"
HTTP/2 302
content-type: text/html; charset=utf-8
location: http://example.com/resolved.jpg
content-length: 0

这可能是预加载/缓存不起作用的原因吗? (我用解析的 URL 代替原始 URL 成功测试了我的代码,并且预加载/缓存工作正常。)

【问题讨论】:

    标签: javascript browser-cache http-redirect preload


    【解决方案1】:

    您可以将图像预加载为 blob,然后使用 blob URL。您可以使用 XHR 请求(您可以使用 xhr.responseURL 来加载 blob)或 fetch API(可以使用 polyfill)。

    let convertUrlToImage = (url) => {
        return fetch(url).then((response) => {
          if (response.redirected) {
            console.log(`redirected to [${response.url}]`)
          } 
          return response.blob();
        }).then((imageBlob) => {
          return new Promise((resolve) => {
            var image = new Image();
            image.src = URL.createObjectURL(imageBlob);
            image.onload = function() {
                resolve(image)
            }
          });
        });
    }
    
    let images = ["flor.jpg", "animal.jpg", "human.jpg"];
    let imagesPromises  = images.map(convertUrlToImage);
    Promise.all(imagesPromises).then((images) => {
        //do whatever with images: Image[];
    });
    

    您可以配置 fetch 以跟随或不跟随重定向,请参阅:https://developer.mozilla.org/en-US/docs/Web/API/Response/redirected

    【讨论】:

      【解决方案2】:

      这里接受的答案是错误的。随后的内容响应是可缓存的(如果提供了适当的标头),但最初的 302 响应绝对不是。并且您的大部分性能成本都在往返于 srrver 的延迟上。虽然您可以返回 301,但我会强烈建议不要这样做。使用 301 很少是正确的。正确的解决方案是对第一个请求做出 200 响应。

      【讨论】:

        猜你喜欢
        • 2014-12-03
        • 2016-06-06
        • 2016-05-31
        • 2013-06-03
        • 2017-02-04
        • 2019-11-01
        • 2011-12-15
        • 2011-11-23
        • 1970-01-01
        相关资源
        最近更新 更多