简体   繁体   中英

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?

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

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM