Skip to content
Grav 2.0 is officially stable. Read the announcement →
Archive

Prevent image loading under certain screen width

Started by Muut Archive 10 years ago · 3 replies · 344 views
10 years ago

Hi,
I was wondering if there's a way to prevent an image to be loaded if the screen width is lower then a certain value, let's say 480px. I know you can hide it by doing "display:none" inside a CSS media query, but that won't prevent the image to be downloaded by the browser.

I was looking at twig's responsive functions ( https://learn.getgrav.org/content/media#responsive-images ) but I can't manage to get it to work.

Thanks in advance!
Federico

PS: I apologize in advance for any grammar mistake!

10 years ago

it's not really possible to get the screen size on the server side. You need JS that runs in the client's browser to determine that.

10 years ago

Ok! I'll look for a JS/ajax solution. Thanks a lot! :)

10 years ago

In case somebody will ask the same question:
I solved the problem by editing the twig template so the image URL is placed in the data-src attribute, and copied by JS in the src attribute only if the screen width is bigger than 480px. Here's the code:

JS

if ($(window).width() > 480) {
  $(".thumb img").each(function() {
     $(this).attr('src', $(this).attr('data-src'))
   });
}
---

Suggested topics

Topic Participants Replies Views Activity
Archive · by Deleted User, 9 years ago
0 1366 9 years ago
Archive · by Muut Archive, 9 years ago
2 940 9 years ago
Archive · by Muut Archive, 9 years ago
2 4069 9 years ago
Archive · by Muut Archive, 9 years ago
1 2960 9 years ago
Archive · by Muut Archive, 9 years ago
3 1125 9 years ago