What I’m trying to do
I am trying to optimize the delivery of images on my blog that is delivered via Obsidian Publish. My site is already delivered on a custom domain via Cloudflare, and I already have the Cloudflare Images product on my account, so I’m trying to use Transform Images to dynamically optimize and cache images via Cloudflare.
Essentially, the process would simply work by prefixing all image URLs so that they are run through the Cloudflare Images infrastructure, so instead of the original image URL from Obsidian Publish:
https://publish-01.obsidian.md/access/fce28e11a3060e1ae5f0c9ef0da24dab/XML%20Aficionado/Files/afalk42_A_highly_detailed_futuristic_humanoid_robot_portrait_ag_ee942afe-312d-44d3-bed2-f6364a68b4bd.png
I would need to be able to programmatically add this prefix to the beginning of the URL:
https://xmlaficionado.com/cdn-cgi/image/width=1000,quality=75,fit=scale-down,format=auto/
So that the final URL in any <img src=“…”> tag would end up being this:
https://xmlaficionado.com/cdn-cgi/image/width=1000,quality=75,fit=scale-down,format=auto/https://publish-01.obsidian.md/access/fce28e11a3060e1ae5f0c9ef0da24dab/XML%20Aficionado/Files/afalk42_A_highly_detailed_futuristic_humanoid_robot_portrait_ag_ee942afe-312d-44d3-bed2-f6364a68b4bd.png
Doing that little image transformation magic would reduce the original .png with a size of 2,043 KB to a tiny little .webp with a size of only 46 KB, in other words a 97.7% reduction in file size, which would be amazing for site performance and user friendliness.
Things I have tried
For some of my other websites that are based on different backends, I have solved this already perfectly by using a Cloudflare Worker to transform the HTML pages and do a dynamic replacement of all <img src=“…”> URLs on the fly.
However, when I tried to apply the same technique to my Obsidian Publish site, this approach did not work, because the HTML code that displays the Obsidian Publish site is not originally part of the HTML page, but rather is dynamically constructed via JavaScript only in the browser on the user’s machine. Hence I am unable to intercept and manipulate the HTML code to insert those URL prefixes.
Has anyone tried to use the publish.js file to do dynamic replacement of image source URLs in an Obsidian Publish site yet? Would that work? Would that code run at the right time, i.e. before those images are actually loaded?