Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Source placeholder for lazy loading images

I'm using a lazyload mechanism that only loads the relevant images once they're in the users viewport.

For this I've defined a data-src attribute which links to the original image and a base64 encoded placeholder image as src attribute to make the HTML valid.

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC" data-src="/path/to/image.png" alt="some text">

I noticed that chrome caches the base64 string but the string is quite long and bloats my HTML (I have a lot of images on a page).

So my question is if it's better to use a small base64 encoded or a 1px x 1px placeholder image?

Note: For SEO purposes the element must be an img. Also my HTML must be valid, so a src attribute is required.

like image 459
damian Avatar asked Jul 10 '15 09:07

damian


1 Answers

You can use this shorter (but valid!) image in the src tag (1x1 pixel GIF):

data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=

Note that if you gzip your HTML (which you should), the length of the string won't be that important because repetitive strings compress well.

Depending on your needs you might want to use a color for the 1x1 pixel (results in shorter gif files). One way to do this is using Photoshop or a similar tool to create the 1x1 pixel GIF in the right color, and then using a tool like ImageOptim to find the best compression. There's various online tools to convert the resulting file to a data URL.

like image 196
thomasfuchs Avatar answered Oct 06 '22 02:10

thomasfuchs