Responsive design - Media Queries - How not to load certain images
Ok, So I designed a responsive layout that doesn't show images for very small screen sizes, using media queries and display: none;
.
So far so good. But these images still download on these devices, causing an increase in bandwidth.
What is the开发者_如何学运维 proper way to make these images not download on the specified devices?
Any response would be much appreciated!
Two options I can think of:
- Detect small devices on the server using browser-sniffing, and send them different HTML that doesn’t reference the images.
- Display the images via CSS instead of HTML (in
style
attributes if you like), using eitherbackground-image
or:before
/:after
andcontent
(not supported by IE 6 or 7), and wrap that CSS code in media queries so that it’s only displayed by devices with larger screens.
The only accessible solution right now is to wrap the image with <noscript>
tags, then pull the image out later with javascript. Cookies don't work on first page load (HTMLPreloadScanner), nor with CDNs. Browser-sniffing is useless if your images aren't always 100% of the viewport.
Slimmage.js implements context-friendly responsive images in 3KB of vanilla JS.
The markup is pretty simple as well:
<noscript data-slimmage>
<img src="http://z.zr.io/ri/1s.jpg?width=150" />
</noscript>
Of course, you can make a server-side helper to even abstract this away.
If you don't mind a javascript dependency you could check window.innerWidth
and insert image tags for sufficiently large screens.
Images would only be requested if javascript is enabled and the window big enough.
If you don't have any issues using additional JavaScript, then you may try THIS. I've stumbled upon it while searching and learning about media queries.
精彩评论