In this tutorial and video, you will learn about 4 different techniques that you can use to boost your websites page performance within Umbraco. These four techniques are:-
- The output cache
- CachedPartial()
- Client Dependency Injection
- Data Caching
The Output Cache
The output cache should be your go-to tool for optimising and caching the backend server-side HTML. Applying the output cache is simple:
The code above is using Duration
to set the cache time to an hour. Duration
is set using seconds rather than minutes, which is why the value is set to 3600 rather than 1. Manually setting the Duration
throughout all of your sites controllers is sub-optimal. It will create a maintenance nightmare in the future. Instead, you should look at using cache profiles:
One way of defining which cache profile a controller should use is via the CacheProfile
property. There are also other alternative techniques to set the cache profile, however, the purpose of this code is to demonstrate that there are more efficient ways of managing the cache compared to Duration
:
CachePartial()
Out-of-the-box, Umbraco ships with a very cool HTML helper that will allow you to easily cache partial views, Cachedpartial()
:
Note, the last parameter is the cacheByPage
parameter. Set this value to true
if you want the partial cache to work on a per-page basis, rather than on a global level!
Client Dependency Framework
The CDF will allow you to optimise any JS and CSS files that your website needs to reference. This framework was built by Shannon Deminick who has written a lot of other cool Umbraco packages. the source code for the framework can be found here. This repository also contains a well-written user guide with some further examples of how to use the framework, so it is worth checking out. The gist of how to use this framework is that you can register CSS and JS files with it. The CDF will bundle, minify it and provide some level of cache key so time can be cached for very long periods. This technique is known as cache-busting which will make your cache strategy a lot more optimal! Using the CDF helper the script and stylesheet files it generates will be rendered on the page:
To render the bundled CSS and JS files you can then use this snippet:
Data Caching
The last type of cache will allow you to cache custom data. This can be handy if you need to call third-party APIs or process data that is complex and time-consuming to retrieve. To access the cache you can use AppCaches
using dependency injection:
To add an item into the cache, you can use GetCacheItem()
:
Getting data from the cache is done in exactly the same way using the same technique: