DEV Community

Cover image for BlurHash as a service with Cloudflare Workers
Ben Taylor
Ben Taylor

Posted on

BlurHash as a service with Cloudflare Workers

Last week I came across BlurHash on twitter. It’s an interesting tool for dealing with image loading issues. Basically it allows you to show a blurred version of an image while the real image is loading over the network. So you can show a kind of preview while it’s loading.

This is a pretty useful technique in terms of UX and perceived performance. It obviously looks a lot nicer, since you’ve got pops of colour and a bit of variety, but the more important part is that users can actively see that the website is loading.

When a user sees just a blank screen or a blank area they can’t get a sense that the page is loading. Maybe it’s broken, or stuck. If you introduce intermediate loading steps it feels to the user like there is an active loading process going on. This is the same concept behind skeleton screens, where a skeleton of the user interface is displayed while the page is loading.

The way BlurHash helps you out is through tooling, not through some specific component implementation. BlurHash gives you two main functions: an encode function and a decode function. The encode function turns the image into a short string of characters (similar to a hash), while the decode function turns a string into a blurred image. Here’s the diagram from their website:

What’s really cool about this is that you can generate the BlurHash string server side when you’re processing images, and then save it along with your model. Then on the client side you can render the blurred image while you’re waiting for the full image to load. Since the blurred image is just a string, you don’t need any sort of binary storage or transfer - just throw it in your JSON or your HTML and get on with it.

The situation this doesn’t work for is when you don’t have full control over server-side processing of your images. You might be consuming images from somebody else’s API, or you outsource your image uploads. I’ve been messing around with Cloudflare Workers a lot recently and it struck me that it would be pretty cool to have a worker do this processing for you.

The full text of this post is available on my Substack, where I go deep into how I implemented BlurHash as a service using Cloudflare Workers.

BlurHash as a Service using Cloudflare Workers

Thanks for reading!

Discussion (0)