Вопрос

I recently found out that the src attribute of an image allows you to put raw base 64 image data straight into it. Am i right in supposing this is technically more efficient than a separate image file as additional requests for the images don't have to be made? Or is the overhead so small that it's not worth it?

Also, assuming i ended up doing this, what would be the best way to get that raw data? (out of, say, an image i whipped up in paint?)

Это было полезно?

Решение

It depends on what you mean by "more efficient". If your measure is time, then it can be more efficient.

The technique you're referring to is using a data URI. Typically you take the image data and base64 encode it so it contains only ASCII characters. base64 encoding data has the effect of making it 33% larger (every 6 bits become 8).

So this works for small images, but for large ones, the 33% premium may be too much.

The reason why it might be a good idea is that latency is often the limiting factor for browser requests. It used to be (back in the day) that bandwidth was the restriction, so the common advice was to split up your resources, but that's not true anymore. With a data URI image, the browser doesn't have to make a second round trip.

Aside from all that, you have to consider browser support. Prior to version 8, IE has no support for data URIs. And in IE 8, there's an upper limit of 32KB of data.

Hope this helps!

Другие советы

There is a size limit to this. I don't know for certain off the top of my head, but 2K seems about right.

Remember that there is overhead for base64 encoding something. If you have a 500 byte image, this might be fine, but for other things, no.

Really though, you shouldn't be doing this right now for compatibility. Maybe in the coming years...

It depends on how many images you're going to be sending and how often they get requested. Having the images in base 64 is absolutely more efficient then 30 http requests.

You could also implement caching of each image if they get requested frequently. This is something we've implemented in my workplace. We store the base64 in a temp directory and check if they've already been encoded. If so, we have an even faster response time, otherwise they get created on the fly in the PHP script. The more popular pages will be warmed up in the cache very quickly.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top