Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Normal image Vs base 64 image [duplicate]

Lets suppose I have an image called - myImage.png
and I'm using it with the <img> tag or as a background-image it doesn't really matter:

<img src="myImage.png" />

So I decide to convert it as a base 64 image:

.myImage {
    background: 0 no-repeat;
    background-image: url(data:image/jpeg;base64,/9j/4AA...SOV//2Q==);
}

The normal size of the image as a .png file, is for example - 60KB.
Then if I create a .css file, paste the chunk of code mentioned above from .myImage and save it, after saving the file its size will be - 60KB as well.

Now my logic is, both images will have the same performance and the same server response because both have the same size, but I'm starting having my doubts and would like to know if does the base 64 image will actually be faster, more lightweight and have a better performance.

like image 276
Chun Avatar asked Mar 16 '23 07:03

Chun


1 Answers

I would only base 64 encode small reusable elements like a simple icon but not a portrait of a person. Something that is 60KB is too large imho. You might save on requests by base 64 encoding your images into your CSS file but after a handful of 60KB images your CSS file is going to get heavy and that's without any actual CSS. Before long you might find yourself with a few MB CSS file and the browser would have to wait for the whole thing to download and then parse before it started rendering the page with your CSS.

For example, a recent project I worked on had a video with a placeholder/poster image with a play button icon over the placeholder/poster image of the video (much like on ESPN's website. The icon was just under 1KB when base 64 encoded along with being used numerous time on the site so it made sense in that instance to bake it into the CSS file.

Browsers today look ahead when parsing an HTML document for images so they can begin requesting and receiving images while the browser waits for other resources like CSS and JS files. Once downloaded, if properly configured on the server with a TTL, your images will be cached for future use and the page will be rendered even faster as the browser will use the images from its cache instead of requesting a copy from the server where your website is hosted.

Base 64 encoding fonts into a CSS file can weigh it down quickly also.

While you might be reducing the number of requests to the server for images, you will be increasing the time it takes to receive another. Test a few things out and see what gives you the best performance. Which is faster? One large file that includes "everything" or multiple yet fast requests?

like image 178
hungerstar Avatar answered Mar 28 '23 04:03

hungerstar