4

I want to change a image when the display is smaller than 400px (for this purpose i cant use the image as background). I thought displaying 1 with display:block and to hide the other with display: none.

My question is if i do it this way, will the browser load both images and hide one of them or will it only load one of them? (display:block). If the browser load both images i need to find a way to change the src of the image

pepote
  • 313
  • 7
  • 21
  • 1
    Yes, browser will load both of the images.. Only after that, one of the image is hidden. – Lal May 05 '15 at 14:59
  • You can use the `` element along with the [picture fill polyfill](https://github.com/scottjehl/picturefill) to support unsupported browsers – Matt Busche May 05 '15 at 15:07

3 Answers3

2

to avoid loading the image twice (not using normal css mediaqueries) you could use window.matchMedia (JS);

var breakpoint = window.matchMedia( "(min-width: 400px)" )

if (breakpoint.matches) {
    // window width is at least 400px
   // you load one img
}
else {
    // window width is less than 400px
    // you load other img
}
maioman
  • 18,154
  • 4
  • 36
  • 42
  • Huh, didn't know about matchMedia. Only [IE10+ support](http://caniuse.com/#feat=matchmedia), but otherwise this looks like a good suggestion! – Timothy Miller May 05 '15 at 15:07
  • 1
    a name you can trust (p.irish) made a [polyfill](https://github.com/paulirish/matchMedia.js/) for that, but there are some issues so please test carefully – maioman May 05 '15 at 15:23
0

ok .. you could check this stackoverflow post, Media queries and background images you must use min-width and mix-width into css and there is a webpage with more information for mediaquery´s assets http://timkadlec.com/2012/04/media-query-asset-downloading-results/

Community
  • 1
  • 1
carlos a.
  • 188
  • 10
0

You could also use responsive images for that - new <picture> tag or srcset attribute for classic <img>. It is nicely explained here:

http://responsiveimages.org/

It is still quite new technique and it'ss not supported by all browsers yet (srcset, picture), however there are polyfills (i.e. Picturefill) that simulate it by JavaScript.

Ondra Koupil
  • 1,034
  • 6
  • 9