Search code examples
htmlcssperformancewordpresspagespeed

What is best practice for images in HTML and CSS


I creating a WordPress theme, and I have implement a function that allowing the images to be served embeded into the HTML document and the CSS files.

What I mean is that instead of adding images in my web site as:

<!-- In HMTL -->
<img src="http://www.some-url.ext/img/my_image.jpg" />

/* In CSS */
selector
{
    background-image: url(http://www.some-url.ext/img/my_image.jpg);
}

to add the image in my site in the following form:

<!-- In HMTL -->
<img src="data:image/gif;base64,R0lG...." />

/* In CSS */
selector
{
    background-image: url(data:image/gif;base64,R0lG....);
}

The processed images are stored in cache files for better performance.

My current theme also has a full width slider, that contains images that are large.

The issue is that the processed document has the size of 1.83MB because of the embeded images.

Also the document while is loading very fast, anything bellow the slideshow is getting slower to be displayed :(

So, is it better to embed the images into the document or is it better to use the normal way with URLs ?


Solution

  • The answer, as usual, is "it depends". Here are some points of interest:

    • Embedding images can speed up pages by reducing the number of HTTP requests, so for lots of little files, it can help.
    • Encoding in base 64 will increase the size of the images by about 1/3.
    • Because the browser has to decode the image, it can slow down rendering.

    See http://en.wikipedia.org/wiki/Data_URI_scheme for a more exhaustive list of pros and cons.

    For large images, I would say you're better off taking the HTTP request hit. You can use various preloading schemes to make the HTTP hits less visible to the user.

    PageSpeed, YSlow, etc., are guidelines, not gospel. As you are finding, you should always test the changes and find out what makes sense for your site.