Google has developed a tool called PageSpeed. It highlighted couple of quick wins I could do to improve website's loading time. Website loading times are one of the most deceptive metrics to measure during development. Website development is frequently done on a local machine when download times are neligiable. It is only once the website goes live, we might begin to release not all is as it seems.
ASP.NET Core, being well thought out, comes with a lot of hacks built-in and it is very easy to make changes even once the production. Here are the main two.
Compression
The most basic performance improvement we can make is adding compression. By default, ASP.NET Core uses Brotli and Gzip compression in 'Fastest' mode. If you are sending more than 10KB for website, it is very likely to improve client's experience.
1 2 3 4 5 6 7 8 9 10 11 12 |
public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddResponseCompression(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseResponseCompression(); } } |
Response Caching for Static Files
The next improvement is to add Cache-Control header to static files. Cache-Control instructs the browser to cache static resources for a specified period of time. There is a truly magnificent article by Ilya Grigorik which describes in great detail how Cache-Control behaves and how to set it up suit needs.
1 2 3 4 5 |
var cachePeriod = env.IsDevelopment() ? "600" : "604800"; app.UseStaticFiles(new StaticFileOptions { OnPrepareResponse = ctx => { ctx.Context.Response.Headers.Append("Cache-Control", $"public, max-age={cachePeriod}"); } }); |