将背景图像数据作为 Base64 嵌入到 CSS 中是好还是坏做法?
我正在查看greasemonkey用户脚本的源代码,并注意到其CSS中的以下内容:
.even { background: #fff url(data:image/gif;base64,R0lGODlhBgASALMAAOfn5+rq6uvr6+zs7O7u7vHx8fPz8/b29vj4+P39/f///wAAAAAAAAAAAAAAAAAAACwAAAAABgASAAAIMAAVCBxIsKDBgwgTDkzAsKGAhxARSJx4oKJFAxgzFtjIkYDHjwNCigxAsiSAkygDAgA7) repeat-x bottom}
我可以理解,greasemonkey脚本希望将其可以包含在源代码中的任何内容捆绑在一起,而不是将其托管在服务器上,这很明显。 但由于我以前没有见过这种技术,所以我考虑了它的使用,并且它似乎很有吸引力,原因有很多:
- 它将减少页面加载时的 HTTP 请求量,从而提高性能
- 如果没有 CDN,那么它将减少通过 cookie 生成的流量与图像一起发送
- CSS 文件可以被缓存
- CSS 文件可以被 GZIPPED
考虑到 IE6(例如)在背景图像缓存方面存在问题,这似乎不是最糟糕的主意...
所以,这是一个好的或坏的做法,为什么你不使用它以及你会使用什么工具来对图像进行 Base64 编码?
更新 - 测试结果
使用图像进行测试:http:// fragged.org/dev/map-shot.jpg - 133.6Kb
专用 CSS 文件: http://fragged.org/dev/base64.css - 178.1Kb
GZIP编码服务器端
发送到客户端的结果大小(YSLOW 组件测试):59.3Kb
保存发送到客户端浏览器的数据:74.3Kb
不错,但我猜对于较小的图像来说,它的用处会稍微小一些。
更新:Bryan McQuade,一位从事 PageSpeed 工作的 Google 软件工程师,在 2013 年 ChromeDevSummit 上表示,CSS 中的 data:uris 被认为是一种阻塞渲染的反模式,用于在他的演讲中提供关键/最小 CSS
# perfmatters:即时移动网络应用程序
。 请参阅 http://developer.chrome.com/devsummit/sessions 并记住这一点 - < a href="https://docs.google.com/presentation/d/1z49qp03iXAJIkbXaMtCmWW_Pnnq-MzXGW139Xw8-paM/edit#slide=id.g174590d5d_0194" rel="noreferrer">实际幻灯片
I was looking at the source of a greasemonkey userscript and noticed the following in their css:
.even { background: #fff url(data:image/gif;base64,R0lGODlhBgASALMAAOfn5+rq6uvr6+zs7O7u7vHx8fPz8/b29vj4+P39/f///wAAAAAAAAAAAAAAAAAAACwAAAAABgASAAAIMAAVCBxIsKDBgwgTDkzAsKGAhxARSJx4oKJFAxgzFtjIkYDHjwNCigxAsiSAkygDAgA7) repeat-x bottom}
I can appreciate that a greasemonkey script would want to bundle anything it can within the source as opposed to host it on a server, that's obvious enough. But since I had not seen this technique previously, I considered its use and it seems appealing for a number of reasons:
- It will reduce the amount of HTTP requests on page load, thus enhancing performance
- If no CDN, then it will reduce the amount of traffic generated through cookies being sent alongside of images
- CSS files can be cached
- CSS files can be GZIPPED
Considering that IE6 (for instance) has problems with cache for background images, this seems like it's not the worst idea...
So, is this a good or bad practice, why WOULDN'T you use it and what tools would you use to base64 encode the images?
update - results of testing
testing with image: http://fragged.org/dev/map-shot.jpg - 133.6Kb
test URL: http://fragged.org/dev/base64.html
dedicated CSS file:
http://fragged.org/dev/base64.css -
178.1KbGZIP encoding server side
resulting size sent to client (YSLOW
components test): 59.3KbSaving of data sent to client browser of: 74.3Kb
Nice, but it will be slightly less useful for smaller images, I guess.
UPDATE: Bryan McQuade, a software engineer at Google, working on PageSpeed, expressed at ChromeDevSummit 2013 that data:uris in CSS is considered a render-blocking anti-pattern for delivering critical/minimal CSS during his talk
#perfmatters: Instant mobile web apps
. See http://developer.chrome.com/devsummit/sessions and keep that in mind - actual slide
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(12)
当您希望单独缓存图像和样式信息时,这不是一个好主意。 此外,如果您将大图像或大量图像编码到 css 文件中,则浏览器将需要更长的时间来下载文件,从而使您的网站没有任何样式信息,直到下载完成。 对于您不打算经常更改(如果有的话)的小图像,这是一个很好的解决方案。
至于生成base64编码:
It's not a good idea when you want your images and style information to be cached separately. Also if you encode a large image or a significant number of images in to your css file it will take the browser longer to download the file leaving your site without any of the style information until the download completes. For small images that you don't intend on changing often if ever it is a fine solution.
as far as generating the base64 encoding:
此答案已过时,不应使用。
1) 2017 年移动设备上的平均延迟要快得多。https://opensignal.com/reports/2016/02/usa/state-of- the-mobile-network
2) HTTP2 多路复用
https://http2.github.io/faq/#why-is- http2 多路复用
移动网站绝对应该考虑“数据 URI”。 通过蜂窝网络进行 HTTP 访问时,每个请求/响应的延迟会更高。 因此,在某些用例中,将图像作为数据塞入 CSS 或 HTML 模板可能对移动 Web 应用程序有益。 您应该根据具体情况来衡量使用情况——我并不提倡在移动 Web 应用程序中的任何地方都使用数据 URI。
请注意,移动浏览器对可缓存文件的总大小有限制。 iOS 3.2 的限制相当低(每个文件 25K),但对于较新版本的 Mobile Safari,限制越来越大(100K)。 因此,在包含数据 URI 时,请务必注意总文件大小。
http://www.yuiblog.com/blog /2010/06/28/mobile-browser-cache-limits/
This answer is out of date and shouldn't be used.
1) Average latency is much faster on mobile in 2017. https://opensignal.com/reports/2016/02/usa/state-of-the-mobile-network
2) HTTP2 multiplexes
https://http2.github.io/faq/#why-is-http2-multiplexed
"Data URIs" should definitely be considered for mobile sites. HTTP access over cellular networks comes with higher latency per request/response. So there are some use cases where jamming your images as data into CSS or HTML templates could be beneficial on mobile web apps. You should measure usage on a case-by-case basis -- I'm not advocating that data URIs should be used everywhere in a mobile web app.
Note that mobile browsers have limitations on total size of files that can be cached. Limits for iOS 3.2 were pretty low (25K per file), but are getting larger (100K) for newer versions of Mobile Safari. So be sure to keep an eye on your total file size when including data URIs.
http://www.yuiblog.com/blog/2010/06/28/mobile-browser-cache-limits/
如果您只引用该图像一次,我认为将其嵌入到您的 CSS 文件中不会有问题。 但是,一旦您使用多个图像或需要在 CSS 中多次引用它,您可能会考虑使用单个图像映射,然后您可以从中裁剪单个图像(请参阅 CSS 精灵)。
If you reference that image just once, I don’t see a problem to embed it into your CSS file. But once you use more than one image or need to reference it multiple times in your CSS, you might consider using a single image map instead you can then crop your single images from (see CSS Sprites).
我建议的一件事是有两个单独的样式表:
一种包含常规样式定义,另一种包含采用 Base64 编码的图像。
当然,您必须在图像样式表之前包含基本样式表。
这样,您将确保尽快下载常规样式表并将其应用到文档,同时您还可以从减少的 http 请求和 data-uris 为您带来的其他好处中获益。
One of the things I would suggest is to have two separate stylesheets:
One with your regular style definitions and another one that contains your images in base64 encoding.
You have to include the base stylesheet before the image stylesheet of course.
This way you will assure that you're regular stylesheet is downloaded and applied as soon as possible to the document, yet at the same time you profit from reduced http-requests and other benefits data-uris give you.
GZipped 后,Base64 使图像大小增加了约 10%,但这超过了移动设备所带来的好处。 由于响应式网页设计已成为总体趋势,因此强烈推荐。
W3C 还建议在移动设备上使用这种方法,如果您在 Rails 中使用资产管道,则这是压缩 css 时的默认功能
http://www.w3.org/TR/mwabp/#bp-conserve-css-images
Base64 adds about 10% to the image size after GZipped but that outweighs the benefits when it comes to mobile. Since there is a overall trend with responsive web design, it is highly recommended.
W3C also recommends this approach for mobile and if you use asset pipeline in rails, this is a default feature when compressing your css
http://www.w3.org/TR/mwabp/#bp-conserve-css-images
我不同意为非编辑图像创建单独的 CSS 文件的建议。
假设图像用于 UI 目的,它是表示层样式,如上所述,如果您正在做移动 UI,那么将所有样式保留在单个文件中绝对是一个好主意,这样就可以缓存一次。
I disagree with the recommendation to create separate CSS files for non-editorial images.
Assuming the images are for UI purposes, it's presentation layer styling, and as mentioned above, if you're doing mobile UI's its definitely a good idea to keep all styling in a single file so it can be cached once.
就我而言,它允许我应用 CSS 样式表,而不必担心复制关联的图像,因为它们已经嵌入其中。
In my case it allows me to apply a CSS stylesheet without worrying about copying associated images, since they're already embedded inside.
我尝试创建一个 CSS/HTML 分析工具的在线概念:
http ://www.motobit.com/util/base64/css-images-to-base64.asp
它可以:
欢迎提出意见/建议。
安东尼
I tried to create an online concept of CSS/HTML analyzer tool:
http://www.motobit.com/util/base64/css-images-to-base64.asp
It can:
Comments/suggestions are welcome.
Antonin
您可以用 PHP 对其进行编码:)
来源
You can encode it in PHP :)
Source
为 Sublime Text 2 的用户带来一些好处,有一个插件可以提供我们在 ST 中加载图像的 Base64 代码。
称为 Image2base64: https://github.com/tm-minty/sublime-text- 2-image2base64
PS:切勿保存插件生成的此文件,因为它会覆盖该文件并会破坏。
Bringing a bit for users of Sublime Text 2, there is a plugin that gives the base64 code we load the images in the ST.
Called Image2base64: https://github.com/tm-minty/sublime-text-2-image2base64
PS: Never save this file generated by the plugin because it would overwrite the file and would destroy.
感谢您提供的信息。
我发现这种嵌入很有用,特别是对于移动设备,尤其是在嵌入图像的 css 文件被缓存的情况下。
为了让生活更轻松,由于我的文件编辑器本身无法处理此问题,我为笔记本电脑/台式机编辑工作制作了几个简单的脚本,在此处共享,以防它们对其他人有任何用处。 我一直坚持使用 php,因为它可以直接且很好地处理这些事情。
在 Windows 8.1 下,
...作为管理员,您可以在路径中建立批处理文件的快捷方式。
该批处理文件将调用 php (cli) 脚本。
然后,您可以右键单击文件资源管理器中的图像,然后发送到批处理文件。
Ok Admiinstartor 请求,然后等待黑色命令 shell 窗口关闭。
然后只需将剪贴板中的结果粘贴到文本编辑器中...
或者
以下应该适用于其他操作系统。
批处理文件...
并且在您的路径中使用 php.exe,调用 php (cli) 脚本...
Thanks for the information here.
I am finding this embedding useful and particularly for mobile especially with the embedded images' css file being cached.
To help make life easier, as my file editor(s) do not natively handle this, I made a couple of simple scripts for laptop/desktop editing work, share here in case they are any use to any one else. I have stuck with php as it is handling these things directly and very well.
Under Windows 8.1 say---
... there as an Administrator you can establish a shortcut to a batch file in your path.
That batch file will call a php (cli) script.
You can then right click an image in file explorer, and SendTo the batchfile.
Ok Admiinstartor request, and wait for the black command shell windows to close.
Then just simply paste the result from clipboard in your into your text editor...
or
Following should be adaptable for other OS.
Batch file...
And with php.exe in your path, that calls a php (cli) script...
据我研究,
使用:
1. 当您使用 svg sprite 时。
2. 当您的图像尺寸较小时(最大 200mb)。
不要使用:
1.当你的图像更大时。
2. 图标为 svg。 因为它们已经很好并且在压缩后进行了 gzip 压缩。
As far as I have researched,
Use :
1. When you are using an svg sprite.
2. When your images are of a lesser size (max 200mb).
Don't Use :
1. When you are bigger images.
2. Icons as svg's. As they are already good and gzipped after compression.