Dmitriy
Dmitriy

Reputation: 93

Load images only for devices with > 640px screen

I have image that should be seen on desktop screens, but not on mobile. I know that CSS media queries are designed only for displaying purposes, which means that on mobile device, image will still be loaded but just not displayed. Is there a way to prevent image from loading on devices with <640px resolution?

Upvotes: 1

Views: 90

Answers (3)

evilReiko
evilReiko

Reputation: 20483

With pure CSS, you can't.

You have two options:

Option 1: HTML5

If you don't need to support old browsers, you can use HTML5 new tag <picture>. Like so:

<picture>
    <source 
        media="(min-width: 641px)"
        srcset="images/my_desktop_image.png">
    <source 
        media="(min-width: 451px)"
        srcset="images/my_mobile_image.png">
    <img 
        src="images/my_default_image.png" 
        alt="picture text">
</picture>

Option 2: Javascript (might be easier with jQuery library)

With jQuery, you can detect window size, and based on that load the desired image:

$(window).resize(function() {
    if($(this).width > 640) {
        // load image..
    }
});

Upvotes: 1

Nisarg Shah
Nisarg Shah

Reputation: 14561

You can check the width of the page on load, and based on that set the src attributes on the images if required.

if(window.innerWidth > 600) {
  document.getElementById("img1").src = "//placehold.it/150";
} else {
  alert("No image loaded");
}
<img id="img1" src="" />

Now, a concern might be that this merges the UI logic (i.e. the URL of the image) into JS. You can avoid that by using a data attribute such as data-src to keep the actual image src and set it dynamically to src based on window.innerWidth. Something like the following:

if(window.innerWidth > 600) {
  var img = document.getElementById("img1");
  img.src = img.attributes["data-src"].value;
} else {
  alert("No image loaded");
}
<img id="img1" src="" data-src="//placehold.it/150" />

Upvotes: 2

멍개-mung
멍개-mung

Reputation: 480

window.onload = function(){
    if(document.body.clientWidth> 600){
        // . . . code . . . 
    }
}

Upvotes: 2

Related Questions