Memory leaks when manipulating images in Chrome

后端 未结 1 1221
[愿得一人]
[愿得一人] 2020-12-05 16:03

I encountered the following 2 (huge!) memory leaks in Chrome:

  1. When editing the \'src\' of an existing image, with new bytes
  2. When using clone() to clon
相关标签:
1条回答
  • 2020-12-05 16:42

    I had the same problem. The only workaround I found was to reduce the number of new Image() to use (ideally one):

    function ImageLoader() {
      var img = new Image();
      var queue = [];
      var lock = false;
      var lastURL;
      var lastLoadOk;
      return { load: load };
    
      function load(url, callback, errorCallback) {
        if (lock) return queue.push(arguments);
        lock = true;
        if (lastURL === url) return lastLoadOk ? onload() : onerror();
        lastURL = url;
        img.onload = onload;
        img.onerror = onerror;
        img.src = url;
    
        function onload() {
          lastLoadOk = true;
          callback(img);
          oncomplete();
        }
        function onerror() {
          lastLoadOk = false;
          if (errorCallback) errorCallback(url);
          oncomplete();
        }
      }
      function oncomplete() {
        lock = false;
        if (queue.length) load.apply(null, queue.shift());
      }
    }
    var loader = new ImageLoader();
    loader.load(url1, function(img) { // do something });
    loader.load(url2, function(img) { // do something });
    

    Note that images will be loaded in serie. If if want to load 2 images in parallel, you'll need to instantiate 2 ImageLoader.

    0 讨论(0)
提交回复
热议问题