What’s the easiest way to go about that? Well, you could use tools like Web Essentials and PngGauntlet to help out, but that doesn’t solve the issue with user-uploaded files. You probably have to modify your website to include *.min.js files, commit them to source control, modify your website project and so on.
It would be much nicer if we didn’t have to worry about any of this and didn’t have to make any modifications to our website. It would be much nicer if it just happened automatically.
With Azure Websites that is now possible. Any web application hosted on Azure Websites no longer have to bother with these types of optimizations anymore.
It doesn’t matter if your website is running ASP.NET, PHP, Node.js or plain static HTML, it works for them all.
All there is needed is to install a NuGet package and publish the website to Azure. Here’s a video demonstrating how to add automatic image optimization.
Here’s what we need:
- Install NuGet package: Azure Image Optimizer
- Install NuGet package: Azure Minifier
- On a web application hosted on Azure Websites
How it works
When they are installed and you publish to Azure Websites, an MSBuild trick makes sure to publish the Webjobs with your web application. As soon as that is done, Azure recognizes the Webjobs and starts them up.
The first time they start up, it can take a little while for them to finish the first pass of optimizations if you have a lot of files to optimize. You might even see the Webjobs restarting in the Azure portal. That’s ok, no problem. They start up immediately again and continues on where they left off.
The Image Optimizer supports .png,.gifand .jpg files. And the Minifier supports .js and .css files.
Server Explorer in Visual Studio shows us the Webjobs along with a log file and a cache file.
The log file is being written to every time a file has been optimized. You can open it by double clicking directly on the .csv file in Server Explorer. The cool thing about using a .csv file is that it an be opened in Excel, so you can easily do more calculations on the data.
The cache file (.xml) contains a list of files and their MD5 hash values. That ensures that the same files aren’t being optimized over and over again each time you publish or restart the WebJob.
If you have enabled Streaming Logs, then you can see the optimizations happen in real time directly within Visual Studio’s Output Window as well.
As always, we keep our source code on GitHub and of course accept pull requests.
These features have been some that both Sayed and I have been wanting to add for a long time, but it was never possible before Microsoft introduced Azure Webjobs, because they required continuously running background tasks to work most reliably and in a way that scales.
The demo website used in the video is also open source and is great for playing around with these two optimizers yourself.