Monday, August 18, 2014

Check if page is cached using Jquery and .Net

Greetings!


A couple of months ago I hit a brick wall when trying to test if a page being loaded was cached or not. To clarify, if a user were to hit "log Out" and redirected to a log out page (while obviously destroying the sessions of course) but then hit the back button, the page would load successfully as if it had not been logged out in the first place (front-end wise). To many .Net developer this can provide a frustrating experience as the Page_Load event in the code behind does not get called when a page is being loaded from cache. After a couple of days of searching, I found the solution (I take no credit for writing the code, I merely found it and edited it but no longer can find the source) which entales a small amount of .Net and Jquery.

For the codebehind, I created a class called CheckCache with the following sub procedure


Dim CookieName As String = "isCached"

Sub setCache(response As HttpResponse, cookieData As String)
response.SetCookie(New HttpCookie(CookieName, cookieData))
End Sub


To walk this through, the CookieName is used to identify the cookie in which we will be accessing. The sub procedure creates the cookie and receives an httpResponse object as well as a string which will contain the data within our cookie we would create when the sub procedure is called.

I then created a js file called CheckCache with the following code


function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}
function setCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}
$(function () {
    $.isCached = (getCookie("isCached") == 'true');
    setCookie("isCached", 'true');
})


The getCookie function retrieves the cookie data by the cookie name. The setCookie function sets the cookie with a value we pass in and receives optional parameters for cookie expiration. Lastly, The ready function contains a variable I created that can be called via jquery to check if the page is cached or not while at the same time setting the value of the cookie to true stating it has been cached (which is normal on document load).

Implementation and how it works:

On each page load (generally a static header control) you want to add the following code on page load


Dim BrowserCache As New BrowserCacheCheck
 BrowserCache.setCache(Response, "False")


When ever the codebehind fires the setCache function on pageLoad, we know that the page is not being loaded in by cache because we know that the page load event DOES NOT get called when a page is cached. Because the codeBehind fires first, it creates the cookie and set its status to False as in "the load request that just came in has not been cached.". After this event fires, our JS ready event fires next as soon as the page is finished loading which sets our jquery variable to false (because the code behind page load event fired and set the cookie to false which means false == true returns false) and then opens the cookie back up and marks it to true.

The reason it opens the cookie back up to true is because we know that a page is cached after the document ready event fires, because we know that we change the cookie to true. Whenever the user hits the back button now, the page load command does not get called thus the cookie still remains true meaning that it's being loaded from cache.

Let me know if I can further clarify this!

No comments:

Post a Comment