Reputation: 1145
There's a similar question here but I think it's for <img>
tags. I'm not really sure if it's the same with background-image
.
I'm making a responsive website and my issue is that I do not want images to load if it's accessed through mobile phones (or if it has a small window width). If the image is just applied with a display: none;
if using @media
, I think there would be wasted time and resources if the image is loaded anyway regardless if it's displayed on mobile phones.
What I need is for images (an <img>
or an element with a background-image
) to only load if it's visible. I'm kinda concerned of somehow optimizing the responsiveness of my site.
If it's done with javascript (or jQuery), it's nice if it's really lightweight. Thanks!
Upvotes: 4
Views: 5752
Reputation: 76
You can also use media queries to remove the call to the background on smaller devices.
So if DIV X loads a BG on desktop you simply apply background-image: none to the same DIV for mobile rez in a min-max query. Do the same for desktop but in reverse so you load smaller or larger images.
So on a responsive site the mobile rez doesn't load an image at all since the .class has been told background-image: none. While the same .class has background-image:img.jpg for higher rez.
Upvotes: 4
Reputation: 21114
Quoting this article:
images [backgrounds] for hidden elements, set via CSS or inline in the element, would load every time, contrary to what we thought/expected.
BUT unused css rules containing a background image are not loaded.
So what you can do, is to dynamically add the background-image class, with javascript/jquery, only if the viewport is larger than X.
Here is a simple demo of how to do it.
HTML
<div id="yourdiv"></div>
CSS
#yourdiv {
background:yellow;
}
#yourdiv.backgrounded {
background:url(your-image.jpg) top left no-repeat;
}
jQuery
$(window).on('load resize',function(){
var w=window,
d=document,
e=d.documentElement,
g=d.getElementsByTagName('body')[0];
var docWidth = w.innerWidth||e.clientWidth||g.clientWidth;
if(docWidth>600){ /* replace 600 with the screen width you want to target */
yourdiv.addClass('backgrounded');
}
});
(jsFiddle doesn't trigger load
, so you've to resize the doc to see it working)
Warning: This will probably cause a "delayed" loading of the image, so be sure to test the results.
Upvotes: 5