简体   繁体   English

Rails:显示带有image_tag或CSS背景图像的图像更好吗?

[英]Rails: Is it better to display images with image_tag or css background image?

I have an image that I need to display prominently/immediately on our index page. 我有一幅图像,需要在我们的索引页面上突出显示/立即显示。 I was wondering whether it would be better to use Rails' image_tag() helper, or use CSS's background image property to render the image quickly. 我想知道使用Rails的image_tag()帮助器还是使用CSS的背景图像属性来快速渲染图像会更好。 Or does it even matter? 还是有关系吗?

If you reference an image in the html of the page, the page has to be parsed and the image downloaded. 如果您在页面的html中引用图像,则必须解析页面并下载图像。

If you reference an image in an external stylesheet, the page has to be parsed, then the CSS has to be downloaded and parsed, then the image needs to be downloaded. 如果您在外部样式表中引用图像,则必须解析页面,然后必须下载并解析CSS,然后需要下载图像。 This will be slower due to the number of round trips to the server to get the image. 由于到服务器获取图像的往返次数将变慢。

If your CSS is inline, then you're back to parsing the first page, then downloading the image. 如果您的CSS是内联的,那么您将返回到解析第一页,然后下载图像。

An interesting option, for the ultimate performance, if your image isn't too big, is to inline your CSS in the page, and then embed the image directly into the CSS, avoiding any downloads after the initial one for the page HTML. 如果您的图像不太大,则为了获得最终性能,一个有趣的选择是将CSS内联到页面中,然后将图像直接嵌入CSS中,从而避免在页面HTML的初始下载后进行任何下载。 eg 例如

<head>
  <style>
    #foo { background-image: url(data:image/png;base64,iVBORw0K...) 
  </style>
</head>
<body>
  <div id="foo"></div>
</body>

Rails (actually SASS) has helpers to inline asset data into CSS files (search for asset-data-url). Rails(实际上是SASS)具有帮助者将资产数据内联到CSS文件中(搜索asset-data-url)。 I've never used it to then inline that CSS into HTML, but this is at least possible. 我从来没有用它来将CSS内联到HTML,但这至少是可能的。

To Rails, it doesn't matter. 对于Rails来说,没关系。 What you choose will end up being based more on how exactly that image is supposed to be displayed. 您最终选择的内容将更多地取决于应该正确显示该图像的方式。 Behind text? 文字后面? As a header image? 作为标题图片? That will guide you to using image_tag or CSS. 这将指导您使用image_tag或CSS。

If the image is considered content, it should be rendered as an image tag with the appropriate alt text. 如果图像被认为是内容,则应将其渲染为带有适当替代文本的图像标签。 If it is decoration, it should be a background image. 如果是装饰,则应为背景图像。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM