简体   繁体   English

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

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

I'm making a request to the server and getting the image url string, inside the component I convert the url to a Base64 string.我正在向服务器发出请求并获取图像 url 字符串,在组件内部我将 url 转换为 Base64 字符串。 And here is the code to do so " I copied it from an answer and can't find it on my history to attribute the author".这是这样做的代码“我从一个答案中复制了它,但在我的历史记录中找不到它来归因于作者”。

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();
      }
    });
  }

in the html page在 html 页

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

the output of the image is around 800KB图像的output大约是800KB
I then store the base64 string in the indexeddb table, and later retrieving the string from the table to display it.然后,我将 base64 字符串存储在 indexeddb 表中,稍后从表中检索字符串以显示它。 My point of doing all of these hassle is to make the website load faster on later visits.我做所有这些麻烦的目的是让网站在以后访问时加载得更快。 But it is not what I expected since it really takes a few seconds to draw the images.但这不是我所期望的,因为绘制图像确实需要几秒钟。 For some pages that contain less images it is reasonable but it gets ugly on other pages.对于包含较少图像的某些页面,这是合理的,但在其他页面上会变得难看。 Is there a more efficient way to do so?有更有效的方法吗?

My point of doing all of these hassle is to make the website load faster on later visits.我做所有这些麻烦的目的是让网站在以后访问时加载得更快。

Why not just set a cache header when you serve the image, and let the browser do the work of saving the cached image for you?为什么不在服务图像时设置一个缓存 header,让浏览器为您保存缓存的图像呢?

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

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

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

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