1

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?

Dmitriy
  • 93
  • 11

3 Answers3

2
window.onload = function(){
    if(document.body.clientWidth> 600){
        // . . . code . . . 
    }
}
멍개-mung
  • 470
  • 5
  • 10
2

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" />
Nisarg Shah
  • 14,151
  • 6
  • 34
  • 55
  • That means the image is not being selected property. Check if its ID matches in the DOM through the developer tools in browser. – Nisarg Shah Oct 17 '17 at 09:51
  • 2
    Thanks, it helped! I just forgot to add "window.onload" so var img couldn't get an actual image, because it was not loaded yet – Dmitriy Oct 17 '17 at 09:52
  • I've faced one more problem. So now when I access website from device <600 it works fine. But when I resize the window the images are not loading. Do you know if there is a way for do this? – Dmitriy Oct 18 '17 at 09:26
  • 1
    @Dmitriy You need to use the [`resize`](https://developer.mozilla.org/en-US/docs/Web/Events/resize) handler for that. – Nisarg Shah Oct 18 '17 at 09:29
1

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..
    }
});
evilReiko
  • 19,501
  • 24
  • 86
  • 102