Recently I have been optimizing the load time for our site Jobping. Getting the browser to really cache a file (not request that file for the duration specified) is something that always takes some time to get right.
So I just wanted to share the code to achieve it and hope it helps someone else out.
TimeSpan duration = TimeSpan.FromMinutes(cacheDurationInMinutes);
HttpCachePolicy cache = HttpContext.Current.Response.Cache;
cache.SetCacheability(HttpCacheability.Public);
cache.SetExpires(DateTime.Now.Add(duration));
cache.SetMaxAge(duration);
cache.AppendCacheExtension("must-revalidate, proxy-revalidate");
FieldInfo maxAgeField = cache.GetType().GetField("_maxAge", BindingFlags.Instance | BindingFlags.NonPublic);
maxAgeField.SetValue(cache, duration);
This will instruct the browser to store a copy of the url andfor the duration given. So be sure that this is applicable for your content before using this code (YMMV).
No comments:
Post a Comment