title: How would I implement loading the average color of an image before it is Loaded?
body: <p>I was wondering how google processes images so that the thumbnails will display a color before loading.</p>
  
  <p>when I search for something the results came like</p>
  
  <p><a href="https://i.stack.imgur.com/WZsFr.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WZsFr.jpg" alt="google images search result"></a></p>
  
  <p>when I inspect the photo it shows that their is an anchor tag with a background color that is like the overall actual image color</p>
  
  <p>and I have a website that is full with images, the website performance is so bad due to the large number of requests  </p>
  
  <p>I used this java script code</p>
  
  <pre><code>function getAverageRGB(imgEl) {
  
      var blockSize = 5, // only visit every 5 pixels
          defaultRGB = {r:0,g:0,b:0}, // for non-supporting envs
          canvas = document.createElement('canvas'),
          context = canvas.getContext &amp;&amp; canvas.getContext('2d'),
          data, width, height,
          i = -4,
          length,
          rgb = {r:0,g:0,b:0},
          count = 0;
  
      if (!context) {
          return defaultRGB;
      }
  
      height = canvas.height = imgEl.naturalHeight || imgEl.offsetHeight || imgEl.height;
      width = canvas.width = imgEl.naturalWidth || imgEl.offsetWidth || imgEl.width;
  
      context.drawImage(imgEl, 0, 0);
  
      try {
          data = context.getImageData(0, 0, width, height);
      } catch(e) {
          /* security error, img on diff domain */
          return defaultRGB;
      }
  
      length = data.data.length;
  
      while ( (i += blockSize * 4) &lt; length ) {
          ++count;
          rgb.r += data.data[i];
          rgb.g += data.data[i+1];
          rgb.b += data.data[i+2];
      }
  
      // ~~ used to floor values
      rgb.r = ~~(rgb.r/count);
      rgb.g = ~~(rgb.g/count);
      rgb.b = ~~(rgb.b/count);
  
      return rgb;
  
  }
  </code></pre>
  
  <p>how to add the rgb color before loading as a placeholder before loading the actual photo , then loading the actual image using lazy image loading technique in order to decrease the number of requests    </p>