Base64 作为背景图像源会导致卡顿并且速度很慢

Base64 as background-image source causes stutter and it is slow

我正在向服务器发出请求并获取图像 url 字符串,在组件内部我将 url 转换为 Base64 字符串。这是这样做的代码“我从一个答案中复制了它,但在我的历史记录中找不到它来归因于作者”。

getBase64Image(img: HTMLImageElement) {
    // We create a HTML canvas object that will create a 2d image
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;
    var ctx = canvas.getContext("2d");
    // This will draw image    
    ctx.drawImage(img, 0, 0);
    // Convert the drawn image to Data URL
    var dataURL = canvas.toDataURL("image/png");
    return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
  }


  getBase64ImageFromURL(url: string) {
    return new Observable((observer: Observer<string>) => {
      // create an image object
      let img = new Image();
      img.crossOrigin = 'Anonymous';
      img.src = url;
      if (!img.complete) {
        // This will call another method that will create image from url
        img.onload = () => {
          observer.next(this.getBase64Image(img));
          observer.complete();
        };
        img.onerror = (err) => {
          observer.error(err);
        };
      } else {
        observer.next(this.getBase64Image(img));
        observer.complete();
      }
    });
  }

在 html 页面中

<div style="background-image:url({{item.imageKey}}); ">
</div>

图像的输出约为800KB
然后我将 base64 字符串存储在 indexeddb table 中,稍后从 table 中检索字符串以显示它。我做所有这些麻烦的目的是让网站在以后访问时加载得更快。但这不是我所期望的,因为绘制图像确实需要几秒钟。对于包含较少图像的某些页面,这是合理的,但在其他页面上会变得难看。有没有更有效的方法?

My point of doing all of these hassle is to make the website load faster on later visits.

为什么不在提供图片时设置缓存 header,让浏览器为您保存缓存的图片?

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Modified-Since