summaryrefslogtreecommitdiffstats
path: root/chrome/browser/resources/downloads/throttled_icon_loader.js
blob: 5a10024e480980df95bd7c7be5dd1b833f845c45 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/** @typedef {{img: HTMLImageElement, url: string}} */
var LoadIconRequest;

cr.define('downloads', function() {
  /**
   * @param {number} maxAllowed The maximum number of simultaneous downloads
   *     allowed.
   * @constructor
   */
  function ThrottledIconLoader(maxAllowed) {
    assert(maxAllowed > 0);

    /** @private {number} */
    this.maxAllowed_ = maxAllowed;

    /** @private {!Array<!LoadIconRequest>} */
    this.requests_ = [];
  }

  ThrottledIconLoader.prototype = {
    /** @private {number} */
    loading_: 0,

    /**
     * Load the provided |url| into |img.src| after appending ?scale=.
     * @param {!HTMLImageElement} img An <img> to show the loaded image in.
     * @param {string} url A remote image URL to load.
     */
    loadScaledIcon: function(img, url) {
      var scaledUrl = url + '?scale=' + window.devicePixelRatio + 'x';
      if (img.src == scaledUrl)
        return;

      this.requests_.push({img: img, url: scaledUrl});
      this.loadNextIcon_();
    },

    /** @private */
    loadNextIcon_: function() {
      if (this.loading_ > this.maxAllowed_ || !this.requests_.length)
        return;

      var request = this.requests_.shift();
      var img = request.img;

      img.onabort = img.onerror = img.onload = function() {
        this.loading_--;
        this.loadNextIcon_();
      }.bind(this);

      this.loading_++;
      img.src = request.url;
    },
  };

  return {ThrottledIconLoader: ThrottledIconLoader};
});