Reputation: 6233
I am looking for the best way to make images (real img
elements, no background-image property) not load on mobile phones. Since using Media Queries and setting display
to none
won´t make the browser stop preloading the images, I researched for better ways using plain CSS/HTML5 without JavaScript. The only way I see is using the HTML5 picture
element to load the image only at certain screen widths.
<picture>
<source media="(min-width: 480px)" src="some.png">
</picture>
However the picture element is not supported by the major browsers yet, so this is not a solution either. Do you have any other idea how to accomplish it? If there is no pure CSS/HTML method what would be the best way using JavaScript?
Upvotes: 2
Views: 4668
Reputation: 1040
For anyone looking for a more modern approach (as of 2019):
<picture>
<source media="(min-width: 1000px)" srcset="***url of image***">
<source media="(max-width: 999px)" srcset="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==" sizes="100%">
<img src="***url of image***" alt="***Image alt***">
</picture>
Upvotes: 10
Reputation: 28564
It would probably be better to start from a mobile-first approach in your case. Start out by not loading any images, and then with JavaScript add the images if some requirement is met. For instance like so with jQuery:
if ($(window).width() > 959) {
$("body").append("<img/>");
}
And if you want to make it responsive/dynamic:
$(window).resize(function() {
if ($(window).width() > 959) {
$("body").append('<img src="path/to/img.jpg" class="responsive-image"/>');
} else {
$(".responsive-image").remove();
}
}).resize();
Upvotes: 1