强制Ajax获取缓存版本

Forcing Ajax to get cached version

本文关键字:版本 缓存 获取 Ajax 强制      更新时间:2023-09-26

我正在创建一个Google Chrome扩展,我希望能够提取一些网站正在加载的图像,并将它们放入扩展中。在某些情况下,这可能会导致对服务器的大量请求,从而有效地降低服务器的速度。这些图像是在用户访问页面时加载的,因此扩展无需再次请求图像。有没有什么方法可以在不再次从服务器中提取数据的情况下获取数据?

使用二进制Ajax,可以将图像作为Blob对象提取,FileReader可以将其转换为base64 URL字符串。

  1. 获取图像的二进制数据作为ArrayBuffer并将其存储在Blob:中

    var oReq = new XMLHttpRequest();
    oReq.open("GET", "/myfile.png", true);
    oReq.responseType = "arraybuffer";
    oReq.onload = function(oEvent) {
      var blob = new Blob([oReq.response], {type: "image/png"});
      // step 2 goes here...
    };
    oReq.send();
    

    (根据规范,你也可以做oReq.responseType = "blob",使oReq.response立即成为Blob,而不是ArrayBuffer。我还不能100%确定这是否真的支持。)

  2. FileReader:读取Blob

    var fr = new FileReader();
    fr.onload = function(e) {
        var dataUrl = e.target.result;
        // step 3 goes here...
    }
    fr.readAsDataURL(blob);
    
  3. 最后,您将URL存储在dataUrl中。将其直接分配给图像元素的src属性:

    document.getElementById("myimg").src = dataUrl;
    

    为了避免将来执行提取,请将数据URL存储在localStorage或IndexedDB存储中。