Does “display:none” prevent an image from loading?

2018-12-31 12:42发布

Every responsive website development tutorial recommends using the display:none CSS property to hide content from loading on mobile browsers so the website loads faster. Is it true? Does display:none not load the images or does it still load the content on mobile browser? Is there any way to prevent loading unnecessary content on mobile browsers?

16条回答
旧时光的记忆
2楼-- · 2018-12-31 13:48

The answer is not as easy as a simple yes or no. Check out the results of a test I recently did:

  • In Chrome: All 8 screenshot-* images loaded (img 1)
  • In Firefox: Only the 1 screenshot-* image loaded that is currently being displayed (img 2)

So after digging further I found this, which explains how each browser handles loading img assets based on css display: none;

Excerpt from the blog post:

  • Chrome and Safari (WebKit):
    WebKit downloads the file every time except when a background is applied through a non-matching media-query.
  • Firefox:
    Firefox won't download the image called with background image if the styles are hidden but they will still download assets from img tags.
  • Opera:
    Like Firefox does, Opera won't load useless background-images.
  • Internet Explorer:
    IE, like WebKit will download background-images even if they have display: none; Something odd appears with IE6 : Elements with a background-image and display: none set inline won't be downloaded... But they will be if those styles aren't applied inline.

Chrome- All 8 screenshot-* images loaded

Firefox- Only the 1 screenshot-* image loaded that is currently being displayed

查看更多
梦醉为红颜
3楼-- · 2018-12-31 13:48

If so is there a way to not load the unnecessary content on mobile browsers?

use <img srcset>

http://www.webdesignerdepot.com/2015/08/the-state-of-responsive-images/

查看更多
伤终究还是伤i
4楼-- · 2018-12-31 13:48

No.The image will be loaded as usual and will still use the user’s bandwidth if you are considering the mobile phone user bandwidth saving.What u can do is to use media query and filter the devices that you want your image to be loaded.Your image must be set as a background image of a div,etc and NOT an tag since the the image tag will load the image regardless if the screen size and the media query set.

查看更多
回忆,回不去的记忆
5楼-- · 2018-12-31 13:48

we're talking about images not loading on mobile, right? so what if you just did an @media (min-width: 400px){background-image:thing.jpg}

wouldn't it then only look for the image at above a certain screen width?

查看更多
登录 后发表回答