将背景图像数据作为 Base64 嵌入到 CSS 中是好的还是坏的做法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1124149/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is embedding background image data into CSS as Base64 good or bad practice?
提问by Dimitar Christoff
I was looking at the source of a greasemonkey userscript and noticed the following in their css:
我正在查看一个greasemonkey用户脚本的来源,并在他们的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:
我可以理解,greasemonkey 脚本希望在源代码中捆绑任何东西,而不是将它托管在服务器上,这很明显。但由于我以前没有见过这种技术,我考虑了它的使用,它似乎很有吸引力,原因有很多:
- 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
- 它将减少页面加载时的 HTTP 请求量,从而提高性能
- 如果没有 CDN,那么它将减少通过与图像一起发送的 cookie 产生的流量
- 可以缓存 CSS 文件
- CSS 文件可以是 GZIPPED
Considering that IE6 (for instance) has problems with cache for background images, this seems like it's not the worst idea...
考虑到 IE6(例如)在缓存背景图像方面存在问题,这似乎不是最糟糕的主意......
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?
那么,这是一个好还是坏的做法,为什么不使用它以及您将使用哪些工具对图像进行 base64 编码?
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.1Kb
GZIP encoding server side
resulting size sent to client (YSLOW components test): 59.3Kb
Saving of data sent to client browser of: 74.3Kb
图像测试:http: //fragged.org/dev/map-shot.jpg- 133.6Kb
专用 CSS 文件: http: //fragged.org/dev/base64.css- 178.1Kb
GZIP编码服务器端
发送给客户端的结果大小(YSLOW 组件测试):59.3Kb
保存发送到客户端浏览器的数据: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/sessionsand keep that in mind - actual slide
更新: Bryan McQuade 是 Google 的一名软件工程师,从事 PageSpeed 的工作,他在 ChromeDevSummit 2013 上表示,CSS 中的 data:uris 被认为是在他的演讲中提供关键/最小 CSS 的渲染阻塞反模式
#perfmatters: Instant mobile web apps
。请参阅http://developer.chrome.com/devsummit/sessions并记住这一点 -实际幻灯片
采纳答案by poop a birck
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.
当您希望单独缓存图像和样式信息时,这不是一个好主意。此外,如果您将大图像或大量图像编码到您的 css 文件中,浏览器将需要更长的时间来下载文件离开您的站点而没有任何样式信息,直到下载完成。对于您不打算经常更改的小图像,如果它是一个很好的解决方案。
as far as generating the base64 encoding:
至于生成base64编码:
- http://b64.io/
- http://www.motobit.com/util/base64-decoder-encoder.asp(upload)
- http://www.greywyvern.com/code/php/binary2base64(from link with little tutorials underneath)
回答by Mike Brittain
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
1) 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
2) HTTP2 复用 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.
对于移动站点,绝对应该考虑“数据 URI”。蜂窝网络上的 HTTP 访问伴随着每个请求/响应的更高延迟。因此,在某些用例中,将图像作为数据插入 CSS 或 HTML 模板可能对移动 Web 应用程序有益。您应该根据具体情况来衡量使用情况——我并不是提倡在移动 Web 应用程序中的任何地方都应该使用数据 URI。
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.
请注意,移动浏览器对可缓存文件的总大小有限制。iOS 3.2 的限制非常低(每个文件 25K),但对于较新版本的 Mobile Safari,限制越来越大(100K)。因此,在包含数据 URI 时,请务必注意总文件大小。
http://www.yuiblog.com/blog/2010/06/28/mobile-browser-cache-limits/
http://www.yuiblog.com/blog/2010/06/28/mobile-browser-cache-limits/
回答by Gumbo
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).
如果您只引用该图像一次,我认为将其嵌入到您的 CSS 文件中没有问题。但是,一旦您使用多个图像或需要在 CSS 中多次引用它,您可能会考虑使用单个图像映射,然后您可以从中裁剪您的单个图像(请参阅CSS Sprites)。
回答by ximi
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.
我建议的一件事是拥有两个单独的样式表:一个包含常规样式定义,另一个包含 base64 编码的图像。
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.
通过这种方式,您将确保您的常规样式表被下载并尽快应用于文档,同时您可以从减少的 http 请求和数据 uris 为您提供的其他好处中获益。
回答by Greg
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.
在 GZipped 之后,Base64 使图像大小增加了大约 10%,但这在移动设备方面超过了好处。由于响应式网页设计有一个整体趋势,因此强烈推荐。
W3C also recommends this approach for mobile and if you use asset pipeline in rails, this is a default feature when compressing your css
W3C 也推荐这种方法用于移动设备,如果您在 Rails 中使用资产管道,这是压缩 css 时的默认功能
回答by tim
I disagree with the recommendation to create separate CSS files for non-editorial images.
我不同意为非编辑图像创建单独的 CSS 文件的建议。
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.
假设图像用于 UI 目的,它是表示层样式,并且如上所述,如果您正在处理移动 UI,那么将所有样式保存在单个文件中绝对是个好主意,以便可以缓存一次。
回答by Antonin Foller
I tried to create an online concept of CSS/HTML analyzer tool:
我试图创建一个 CSS/HTML 分析器工具的在线概念:
http://www.motobit.com/util/base64/css-images-to-base64.asp
http://www.motobit.com/util/base64/css-images-to-base64.asp
It can:
它可以:
- Download and parse HTML/CSS files, extract href/src/url elements
- Detect compression (gzip) and size data on the URL
- Compare original data size, base64 data size and gzipped base64 data size
- Convert the URL (image, font, css, ...) to a base64 data URI scheme.
- Count number of requests which can be spared by Data URIs
- 下载并解析 HTML/CSS 文件,提取 href/src/url 元素
- 检测 URL 上的压缩 (gzip) 和大小数据
- 比较原始数据大小、base64 数据大小和 gzip 压缩后的 base64 数据大小
- 将 URL(图像、字体、css 等)转换为 base64 数据 URI 方案。
- 计算数据 URI 可以节省的请求数
Comments/suggestions are welcome.
欢迎提出意见/建议。
Antonin
安东尼
回答by Rolf
In my case it allows me to apply a CSS stylesheet without worrying about copying associated images, since they're already embedded inside.
就我而言,它允许我应用 CSS 样式表而不必担心复制关联的图像,因为它们已经嵌入其中。
回答by ucefkh
You can encode it in PHP :)
您可以在 PHP 中对其进行编码 :)
<img src="data:image/gif;base64,<?php echo base64_encode(file_get_contents("feed-icon.gif")); ?>">
Or display in our dynamic CSS.php file:
background: url("data:image/gif;base64,<?php echo base64_encode(file_get_contents("feed-icon.gif")); ?>");
1 That's sort of a “quick-n-dirty” technique but it works. Here is another encoding method using fopen() instead of file_get_contents():
<?php // convert image to dataURL
$img_source = "feed-icon.gif"; // image path/name
$img_binary = fread(fopen($img_source, "r"), filesize($img_source));
$img_string = base64_encode($img_binary);
?>
回答by Daniel Santarriaga
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.
为 Sublime Text 2 的用户带来一些好处,有一个插件提供了我们在 ST 中加载图像的 base64 代码。
Called Image2base64: https://github.com/tm-minty/sublime-text-2-image2base64
称为 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.
PS:永远不要保存插件生成的这个文件,因为它会覆盖文件并会破坏。