I was wondering how google processes images so that the thumbnails will display a color before loading.
when I search for something the results came like
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
and I have a website that is full with images, the website performance is so bad due to the large number of requests
I used this java script 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 && 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) < 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; }
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
Advertisement
Answer
Step one is to prevent the image load up front. For images loaded using the tag, the browser uses the src attribute of the tag to trigger the image load. Irrespective of whether it is the 1st or the 1000th image in your HTML and well off-screen, if the browser gets the src attribute, it would trigger the image load.
Thus, to lazyload such images, put the image URL in an attribute other than src. Let’s say we specify the image URL in the data-src attribute of the image tag. Now that src is empty, the browser doesn’t trigger the image load
Now that we’ve stopped the upfront load, we need to tell the browser when to load the image.
For this, we check that as soon as the image (i.e., its placeholder) enters the viewport, we trigger the load.