Hi,
I just thought I'd share this here, as it is something that took me a while to figure out. I'm using the gallery addon with modx revolution, and I wanted to have responsive images. So users with a small screen size only have to download small images, which is a tremendous speedboost for mobile users.
There are a lot of solutions out there, but my demands were specific:
- Uses the img tag (so no picturefill)
- Is cacheable over a CDN (so adaptive images was out, since it uses dynamic images)
- Is based on user window resolution, not connection speed (so hisrc was out as well)
I ended up using a javascript/jquery based srcset polyfill, which can be found here:
https://github.com/JimBobSquarePants/srcset-polyfill. Srcset.js needs the following syntax with an image in order to work:
<img src="small.jpg"
srcset="small.jpg 1w,
medium.jpg 320w,
large.jpg 500w" />
The srcset attribute lets the script know where the different versions can be found. What I did is use the gallery addon to retrieve the large master-image, and resize that when necessary using phpthumbof. So for example for one image, this is what I used:
<img src="[[!phpthumbof? &input=`large.jpg` &options=`&w=320&zc=0`]]"
srcset="[[!phpthumbof? &input=`large.jpg` &options=`&w=320&zc=0`]] 1w,
[[!phpthumbof? &input=`large.jpg` &options=`&w=500&zc=0`]] 320w,
large.jpg 500w" />
To make this usable for all my images, I created a chunk called "srcset.returnimg", which I call for the file example.jpg using the following syntax:
[[!$srcset.returnimg? src=`example.jpg`]]
The code for this chunk looks like this:
<img src="[[!phpthumbof? &input=`[[+src]]` &options=`&w=320&zc=0`]]"
srcset="[[!phpthumbof? &input=`[[+src]]` &options=`&w=320&zc=0`]] 1w,
[[!phpthumbof? &input=`[[+src]]` &options=`&w=500&zc=0`]] 320w,
[[+src]] 500w" />
And this outputs the responsive images for each image you send to it. It also gives you convenient control over the breakpoints you're using for your images with one chunk.
If you want to use this chunk with the gallery addon, you can just use the call to $srcset.returnimg in a template, and gallery will automatically output all your images as responsive images. I hope this is of use to someone, it works marvellously for me. Since the urls that phpthumbof outputs are static I can even have cloudflare cache them, which means even faster downloads for mobile users.
The only potential downside is that users who have javascript turned off get to see the small version regardless of their window resolution. But that is something I'm fine with, and you could fix this with an img in a noscript tag and display:none for the responsive img. The extra overhead for also downloading the responsive img would be only a minor penalty.
[ed. note: c.reiss last edited this post 13 years, 1 month ago.]