Chris
Chris

Reputation: 6233

How to not load images on mobile phones?

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

Answers (2)

theCuriousOne
theCuriousOne

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>

  • If the width of the browser is greater than 1000px then show url of image
  • If the width of the browser is less than 1000px then show image represented as base64 data (which can be just a 1px in size), and in this way nothing is downloaded from the server.
  • Fallback (if the browser does not support this) - use the good old tag

Upvotes: 10

Bram Vanroy
Bram Vanroy

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

Related Questions