使用背景而不是内嵌图像来通过媒体查询进行移动优化?

发布于 2024-12-11 12:16:48 字数 614 浏览 0 评论 0原文

我通过媒体查询在移动设备上优化了我的网站。一切看起来都如我所愿,但正在下载不必要的图像(因为它们隐藏在 CSS 中),从而减慢了页面加载时间。

最简单的解决方案似乎是用带有背景图像的 div 替换尽可能多的内联图像。然后我可以使用移动版本的媒体查询 css 隐藏 div。

我知道这有潜在的缺点,这篇文章中概述了这一点: 何时使用 IMG 与 CSS 背景图像?

公司徽标、员工照片等将保留为内嵌图像。

我的方法是否存在我没​​有考虑到的问题?我读过很多关于移动优化的内容,特别是媒体查询方面的内容,而且我还没有听说有人这样做,尽管这似乎是一个相当明显的解决方案,其中图像可以内联或背景。

请注意,我用 iPhone 和 Android 做了一些实验(我正在等待获得一些黑莓),并且我知道要停止下载背景图像,我需要将“不显示”设置为 div 的父级,而不是具有背景图像本身的 div。

注意2,在理想的情况下,网站可能首先构建为移动端,但在这种情况下(通常在其他情况下),原始网站的修改量是有限的。

谢谢

Ive mobile optimised my site with media queries. Everything looks how I would like it to but unnecessary images (as they're hidden with css) are being downloaded, slowing page loading times.

The easiest solution to this seems to be to replace as many inline images as I can with divs with background images. Then I can hide the div's with media query css for the mobile version.

I know there are potential downsides to this, outlined well in this post:
When to use IMG vs. CSS background-image?

So the company logo, pictures of staff, etc will stay as inline images.

Are there any issues to my approach I havn't considered? Ive read a lot about mobile optimisation, particularly with media queries, and I havn't heard of anyone doing this even though it seems quite an obvious solution where images could be inline or background.

Note, ive done some experiments with iPhones and Android (im waiting to get some Blackberrys) and I know to stop background images downloading I need to set display none to the div's parent, not the div with the background image itself.

Note2, in an ideal world sites would probably have been built as mobile first but in this situation (and often in others) there is a limit to how much the original site can be modified.

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

凉栀 2024-12-18 12:16:48

不幸的是,对于您试图解决的问题没有很好的答案。

首先,您可以选择将所有内容从 img 标签移动到 css 背景图像。正如您所指出的,您必须小心这样做会失去语义。

但即使您可以在不丢失语义值的情况下转移到背景图像,它仍然不是 100% 可靠。去年夏天我写了一系列测试。上周我重新测试了它们,为我们书中有关移动优先响应式网页设计的章节做准备。测试位于 http://www.cloudfour.com/examples/mediaqueries/image -测试/

不幸的是,Android 未能实现所有这些技术。您可以看到它通过 Blaze 的移动测试下载图像文件的多个副本:
www.blaze.io/mobile/result/?testid=111031_96_316

2011 年 11 月 3 日更新:我目前正在尝试协调在 Blaze 上看到的结果与亲自使用同一设备看到的结果之间不一致的结果。在我本地的 Nexus S 上,它通过了第五个 css 测试,该测试通过将 imgs 放入媒体查询中来限制它们。我查看了 apache 日志,并确认该设备在测试 5 中仅下载一张图像而不是两张。Blaze 正在运行 2.3.3。我的手机运行的是2.3.6。

Android 2.2、2.3 和 3.0 都是如此。希望 4.0 能够包含 webkit 修复程序来防止这种行为:
bugs.webkit.org/show_bug.cgi?id=24223

顺便说一句,这似乎与您关于测试将父 div 设置为在 Android 上显示的评论相冲突。如果您得到不同的结果,我很想听听。

如果你将它们保留为 img 标签,你有什么选择?关于这个主题,我写了一个由多个部分组成的系列。本系列的第二部分深入介绍了不同的技术:
http://www.cloudfour.com/responsive-imgs-part-2/

再说一遍,没有一个解决方案是好的。如果您想要简单且在大多数情况下都能工作的东西,我会选择adaptive-images.com。或者通过 Sencha.io SRC 路由图像,直到我们有更好的解决方案来解决这个问题。

顺便说一句,很抱歉有这么多实际上不是链接的链接。这是我在 stackoverflow 上的第一个回复,它只允许我包含两个链接。

Unfortunately, there are no great answers for the problems you’re trying to solve.

First, you have the option of moving everything from img tags to css background images. As you note, you have to be careful of losing semantic meaning by doing so.

But even if you can move to background images without losing semantic value, it is still not going to be 100% reliable. I wrote a series of tests last summer. I retested them last week in preparation for the chapter in our book on mobile first responsive web design. The tests are located at http://www.cloudfour.com/examples/mediaqueries/image-test/.

Unfortunately, Android fails every one of those techniques. You can see it downloading multiple copies of the image files via Blaze’s mobile test:
www.blaze.io/mobile/result/?testid=111031_96_316

UPDATE 3 Nov 2011: I’m currently trying to reconcile inconsistent results between what I see on Blaze and what I see using the same device in person. On my local Nexus S, it passes the fifth css test which limits the imgs by putting them inside the media queries. I watched the apache logs and confirmed the device only downloads one image instead of two for test 5. Blaze is running 2.3.3. My phone is running 2.3.6.

This is true for Android 2.2, 2.3 and 3.0. Hopefully, 4.0 will incorporate the webkit fixes that prevent this behavior:
bugs.webkit.org/show_bug.cgi?id=24223

BTW, this seems to conflict with your comment about testing setting the parent div to display:none on Android. If you’re getting different results, I’d love to hear about it.

If you keep them as img tags, what are your options? On this topic, I have written a multi-part series. The second part in the series provides an in-depth look at the different techniques:
http://www.cloudfour.com/responsive-imgs-part-2/

Again, none of the solutions are great. If you want something that is simple and will work most of the time, I’d go for adaptive-images.com. Or route images through Sencha.io SRC until we have a better solution for this problem.

BTW, sorry for having so many links that aren’t actually links. This is my first response on stackoverflow and it will only allow me to include two links.

泪眸﹌ 2024-12-18 12:16:48

为什么不采用移动优先的方法,然后使用媒体查询来增强更大的屏幕。

您还可以使用媒体查询来提供特定的 CSS 文件。

对于内联图像,我尝试了在头部和开始正文标记之后立即使用脚本块,该脚本块仅针对移动设备运行(通过添加到正文的类名进行检测,或是否存在媒体查询 CSS 文件),以查找所有内联图像某个类并清空 src 属性。

请参阅此处 防止图像加载

<script type="text/javascript" charset="utf-8">
    $(document).ready( function() { $("img").removeAttr("src"); } );
</script>

另一种方法是使用带有 mod rewrite 的 url 重写和 . htaccess 或 iis 的 url 重写模块。将手机的用户代理字符串重定向到一个小的空白图像。

看:
一种防止移动浏览器下载和显示图像

RewriteCond %{HTTP_USER_AGENT} (nokia¦symbian¦iphone¦blackberry) [NC] 
RewriteCond %{REQUEST_URI} !^/images/$
RewriteRule (.*) /blank.jpg [L]

您可以通过从不同的子域加载内联图像并仅重写移动图像来改进上述内容,因为您不想重写所有图像(徽标等)

Why not do a mobile first approach and then use media queries to enhance bigger screens.

Also you can use media queries to serve specific CSS files.

With the inline images I have tried a script block in the head and immediately after the opening body tag, which runs only for mobile devices (detect via classname added to body, or presence of a media query CSS file) that find all inline images with a certain class and empty the src attribute.

see here Prevent images from loading

<script type="text/javascript" charset="utf-8">
    $(document).ready( function() { $("img").removeAttr("src"); } );
</script>

another way is to use url re-writing with mod rewrite and .htaccess or url rewrite module for iis. redirect user agent strings for mobiles to a small blank image.

see:
A way to prevent a mobile browser from downloading and displaying images

RewriteCond %{HTTP_USER_AGENT} (nokia¦symbian¦iphone¦blackberry) [NC] 
RewriteCond %{REQUEST_URI} !^/images/$
RewriteRule (.*) /blank.jpg [L]

you can improve the above by loading your inline images from a different sub-domain and rewriting only those for mobile, as you don't want to rewrite all images (logo etc.)

你如我软肋 2024-12-18 12:16:48

如果我正确理解您的问题,这似乎是 srcsetsizes 的完美用例。 这篇 MDN 文章是学习概念深入,但我也会在这里总结一下。这是一个完整的、有点复杂的示例:

<img srcset="elva-fairy-320w.jpg 320w,
         elva-fairy-480w.jpg 480w,
         elva-fairy-800w.jpg 800w"
     sizes="(max-width: 320px) 280px,
        (max-width: 480px) 440px,
        800px"
     src="elva-fairy-800w.jpg" 
     alt="Elva dressed as a fairy">

这段代码表示:

  • 如果我的浏览器不支持 srcset,则默认使用 src 中的内容。不要忽略这一点。
  • 嘿浏览器,在 srcset 中,这里有 3 个文件,它们的自然宽度用逗号分隔。
  • 嘿浏览器,这里的 sizes 是我希望图像根据媒体查询占用的空间宽度。使用第一个匹配的那个。

然后浏览器本身将根据用户的尺寸和屏幕分辨率计算出哪张是最好使用的图像,然后只下载我书中非常棒的一张。

If I'm understanding your question correctly, this seems like a perfect use case for srcset and sizes. This MDN article is a great post for learning the concept in-depth, but I will also summarize here. Here is a full, kind of complicated example:

<img srcset="elva-fairy-320w.jpg 320w,
         elva-fairy-480w.jpg 480w,
         elva-fairy-800w.jpg 800w"
     sizes="(max-width: 320px) 280px,
        (max-width: 480px) 440px,
        800px"
     src="elva-fairy-800w.jpg" 
     alt="Elva dressed as a fairy">

This code says:

  • If my browser doesn't support srcset use what is in src by default. Don't leave this out.
  • Hey browser, in srcset, here are 3 files and their natural widths separated by commas.
  • Hey browser, in sizes here are the widths of the space I want my image to take up depending on the media query. Use the one that matches first.

Then the browser itself will calculate which is the best image to use based on size AND screen resolution of the user then ONLY downloads that one which is pretty awesome in my book.

窗影残 2024-12-18 12:16:48

好的,需要注意的重要一点是移动!=低带宽!=小屏幕,桌面!=高带宽!=大屏幕。

您可能想要的是根据客户端带宽和客户端屏幕尺寸做出决定。媒体查询仅对后者有帮助。

David Calhoun 在这里写了一篇关于如何执行此操作的精彩文章:http://davidbcalhoun.com/2011/ mobile-performance-manifesto

强烈推荐。

Ok, important thing to note is that mobile != low bandwidth != small screen and desktop != high bandwidth != large screen.

What you probably want is to make a decision based on client bandwidth and client screen size. Media queries only help with the latter.

David Calhoun has a great writeup on how to do this here: http://davidbcalhoun.com/2011/mobile-performance-manifesto

Highly recommended.

千笙结 2024-12-18 12:16:48

我最近偶然发现了一篇关于该主题的精彩博客文章,解决了响应式图像问题(即在较小的设备上提供较小的图像)。文章的评论是最有趣的部分,我认为 Weston Ruter 创造的替换技术是一种很有前途的技术:

http://jsbin.com/ugodu3/13/edit#javascript,html,live
(查看评论中的其他迭代)。

它有很多警告(并且可能很困难,但并非不可能,合并到现有网站中,因为会影响所有非绝对链接,而不仅仅是 imgs),但我会在我的网站上尝试它(与延迟加载合并)下一个项目,这是一个响应式网站,我的设计师做得相当重(而且他不想让它变得更轻)。请注意,如果您的服务器支持,您可以将其组合到一个 php 脚本中,根据需要调整图像大小。

响应式图像的其他常见解决方案是基于 cookie 的(检查 Filament Group 响应式图像插件)。

与 css 背景相比,我更喜欢响应式图像,因为它们在语义上更正确,并且在 SEO 方面可解析。如果我同意我们不应该假设更大的屏幕 = 更多的带宽,那么我们缺乏解决这个问题的工具(navigator.connection 仅适用于 Android。)因此假设大多数移动用户的 2G/3G 连接很差是最安全的方法。

I stumbled recently on a great blog article on the subject, adressing the problem of responsive images (ie serving smaller images on smaller devices). The comments of the article are the most interesting part, and I think the replacement technique coined by Weston Ruter is a promising one :

http://jsbin.com/ugodu3/13/edit#javascript,html,live
(look at the other iterations in the comments).

It has lots of caveat (and is maybe difficult, but not impossible, to merge in an existing website, as the affect all your non absolute links, not only imgs), but I will try it (merged with a lazy loading) on my next project, which is a responsive website that my designer made quite heavy (and he does not want to make it lighter). Note that you could combine this to a php script resizing the images on demand if your server supports it.

The others common solutions for responsive imgs are cookie based (check Filament Group Responsive images plugin).

I prefer responsive images to css background because they're more correct semantically and parse-able SEO-wise. If I agree that we should not assume that bigger screen = more bandwidth, we lacks tools to address this (navigator.connection is Android only.) so assuming that most mobile users have a crappy 2G/3G connection is the safest way.

雨后彩虹 2024-12-18 12:16:48

我不确定您是否考虑过这样做,但您可以做的一件事是使用 javascript 检查屏幕分辨率的宽度,然后分辨率是否小于某个数字(我使用 480,因为此时网站看起来很糟糕),然后将 CSS 模板从默认模板切换为移动主题模板。

function alertSize() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  }
  if (myWidth < 48)
  {
   switch css template to mobile template
  }
}

I'm not sure if you have thought about doing this but one of the things you can do is check for the width of the screen resolution with javascript and then if the resolution is less than some number (I use 480 because at that point that site looks bad) then switch the css templates from the default to the mobile themed template.

function alertSize() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  }
  if (myWidth < 48)
  {
   switch css template to mobile template
  }
}
孤千羽 2024-12-18 12:16:48

适应现有的网站很糟糕,但我们做了我必须做的事情。以下是我将博客提要导入移动网站时解决该问题的方法。仅当页面上的现有图像大于屏幕时,它才会将其缩放到页面的宽度。

var $images = $("img[width]");
    $images.each(function(){ 
      try{
          var $image = $(this);
          var currentWidth = Number($image.attr("width"));
          if(currentWidth > screen.width){
              $image.width("100%");
              $image.removeAttr("height");
           }
      }
      catch(e)
      {/*alert("image scale fail\n"+e)*/}
 });

通过将宽度设置为 100% 并删除任何高度属性,无论您处于横向还是纵向,图像都将完美缩放以占据整个宽度。

您的常规网站上的图像很可能已经经过网络优化。加载较小的图像通常不会获得太大的性能提升。减少 HTTP 请求比引入较小的图像更能提高性能。它可能不是完美的解决方案,但肯定是维护最少的。如果您无法合理控制网站上使用的图像,这是一个非常合理的解决方案。如果不出意外的话,也许这会激发你的另一个想法。

Adapting to an existing site sucks but we do what me must. Here is how I solved it when importing a blog's feed into a mobile site. It scales the existing image on the page to the page's width ONLY if it's larger than the screen.

var $images = $("img[width]");
    $images.each(function(){ 
      try{
          var $image = $(this);
          var currentWidth = Number($image.attr("width"));
          if(currentWidth > screen.width){
              $image.width("100%");
              $image.removeAttr("height");
           }
      }
      catch(e)
      {/*alert("image scale fail\n"+e)*/}
 });

By making the width 100% and removing any height attribute, the image will scale perfectly to take up the full width whether you're in landscape or portrait orientation.

Chances are, the images on your regular site are already web optimized. There's usually not that much performance boost to be gained by loading smaller images. Reducing HTTP requests will make much more of a performance boost than bringing over smaller images. It may not be the perfect solution but it is certainly going to be the least maintenance. If you can't reasonably control what images are going to be used on the site, this is a pretty reasonable solution. If nothing else, maybe this will spark another idea for you.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文