I've been doing this for years. Works every time. I helped a big e-comm site shave over 300k from their image payload with this trick alone!
Hah this comment sounds like a shaky clickbait title ☺️
lol, I feel very stupid right now.
But, that being said, you can also just use the srcset attribute for this.
Yep, srcset is the best solution for this.
Srcset defeats the whole purpose of only having to manage 1 image. Plus the retina image is smaller for non-retina as well.
srcset is best for "art directed" images - changing the image slightly based on resolution/width of the viewport.
This single jpeg trick is great if simply scaling the image up and down.
Agreed. Especially as the content changes from wide to tall, the image often must change shape entirely.
Even if the image is identical at every size,
srcsetis also going to give you more reliable results if you don't know what the image will be beforehand (e.g. making a template page that's going to get loaded into a CMS), because you can't tweak the compression settings and then check the results to make sure your images aren't ruined.
Tweaking compression is also not an option for the sort of images you'll want to load as PNGs (e.g. logos), although if you've got lots of blocks of solid colour a @4x PNG might not be much bigger than the @1x, so you might as well just serve the @4x. (Yes, there are phones which use @4x; not tablets or desktops yet though.)
That said, for most of the cases where you want a PNG, you might really want a SVG (remembering that SVG files are uncompressed XML, so you need to make sure your server is set to compress them with gzip or brotli, and look at what the file size is then).
Did you even open the link at all? Why are you even talking about SVG? There is no such thing as an SVG image. SVGs are vector not raster.
Yes, the retina image is smaller (by 600bytes according to dev tools), but the 80% compression is noticeable. Don't get me wrong, this trick is useful in some situations, but it isn't a solution since some images will look terrible when you compress them this much.
Using a decent build system, workflow or even a CMS that allows users to upload a single image before being processed and output to a variety of sizes are arguably more reliable and higher quality solutions - you can automate this entirely and forget about managing assets so much.