title: Javascript: How to check if image is already cached
body: <p>I just started to learn a little bit of JavaScript and i wondered if there is a way to check if an image is already loaded to cache.</p>
  
  <p>In my script im loading some random images from another webpage and display them.
  When the same image will be displayed the second time, the script won't use the already loaded image, but instead load the same image again, so that there are two of them stored in my cache.</p>
  
  <p>Now I want to check if the image is already stored in cache and if so, use the cached one instead of loading it again.</p>
  
  <p>My code:</p>
  
  <pre><code>&lt;script&gt;
      var img = document.createElement('img');
      var index;
  
      //On Click create random 3digit number between 1 and 100
      document.getElementById('image').onclick = function(){
          var index = '' + Math.floor(Math.random() * 100 +1);
  
          while(index.length &lt; 3) {
              index = '0' + index;
          }
  
          loadImages(index);
      };
  
      //Load the image with the created number
      function loadImages(id) {
          var src = 'someWebPage/' + id +'.png';            
  
          img.onload = function () {
              document.getElementById('image').getContext("2d").drawImage(img, 0, 0, 300, 300);
          }
  
          img.src = src;            
      } 
  &lt;/script&gt;
  </code></pre>
  
  <p>Picture of my cache:</p>
  
  <p><a href="https://i.stack.imgur.com/QsSvH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QsSvH.png" alt="enter image description here"></a></p>
  
  <p>As you can see <code>030.png</code> and <code>032.png</code> are twice in cache.</p>
  
  <p>Hope you can give me some advice.</p>
  
  <p><strong>EDIT:</strong>
  Just for anyone else that faces this problem, it actually isn´t one at all.
  Chrome already did everything right, i only did not notice.
  <a href="https://i.stack.imgur.com/W5XwQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/W5XwQ.png" alt="enter image description here"></a>
  As you can see in the column <code>Size</code> the pictures were already loaded from my cache.</p>