politemikey politemikey - 5 months ago 18x
HTML Question

What is the best method to hide <img> on mobile devices?

in my html I have four

tags which I want to hide on mobile devices and I'm looking for best method to do it without downloading them on mobile.
I found out that using
in CSS doesn't prevent browser from downloading image, also I know how to use
attribute to source shuffling based on media queries but I don't know if it's posible to use it to hide content based on media queries.

Does anyone know how to do it properly ?


Another way might be to not add values to the src attributes until you've figured out what the device is. Load the elements with the class identifying the device:

<img class="desktop" data-src="http://dummyimage.com/200x200/000/fff" />

Then once you've identified the device, add the URL in the data attribute to src for each affected image:

var images = document.querySelectorAll('img.desktop');

for (let i = 0; i < images.length; i++) {
  images[i].src = images[i].dataset.src;