I am working on a site that has an international audience and that needs to allow users to toggle a "low bandwidth" version. In order to achieve this, I would like to check if a cookie has been set and if so, override the global JPEG quality value from 75% down to, for example, 40%.

How can I override this variable and is this even possible with image caching?

  • by "low bandwidth" version are you referring to mobile devices?
    – No Sssweat
    May 19 '17 at 11:09
  • Not necessarily. The site is already responsive and works great on mobile devices, it's just by nature quite image heavy and we would like to be able to allow users on slower internet connections to be able to load pages in a reasonable amount of time. May 19 '17 at 11:10
  • 1
    Assuming you're using Image style quality module? Perhaps just create additional "low quality" styles, and switch up the style by checking the cookie? Even if you're using rendered nodes, it should be possible to override the image style programmatically using various hooks. This also won't get affected by caching since the derivatives of 2 different styles should be stored separately.
    – Beebee
    May 19 '17 at 11:19
  • That's a really good idea actually, since the main ones I want to target are large image banner sliders which is just the one style at the moment. I'll give this a go and post some code here if it's successful. Thanks! May 19 '17 at 11:34

This would need a bunch of image styles, a custom field formatter, a custom module that reads that cookie value, and a speed test of some sort.

  1. You'd need to create image styles for each of the quality tiers that you want. That part can be done with the built-in image styles module.

  2. Then you'd want to create a custom module that:

    • Detects the speed of the client's connection and sets that cookie. It can simply be JS downloading a 1KB file download whose start and end times are recorded and set on a cookie.

    • Supplies a custom field formatter to image fields that, instead of making you select a fixed quality, will select the image style and render the image with that image style on-the-fly. As an added bonus, you could allow the formatter to be configurable by exposing a form that allows the selection of which image style to use at certain speeds.

    • Lastly, detects the cookie that was set earlier and informs the field formatter which image style to use based on the cookie value.

This assumes that all imagery are coming from fields (because of the field formatter). For theme imagery, you'll need to render your images by hand in the same way as above, sans the field formatter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.