I've been using a lot of JQuery and JTemplates after reading a couple really helpful JQuery and MVC posts at Encosia.com. One problem I ran into while doing some development on a new .Net MVC Project that was using JQuery extensively was that my template files were being cached by my browser. I tried clearing the cache but that wasn't helping, so here's a workaround I came up with.
If you take a look at how JQuery's $.ajax(...) function handles the caching problem you can see that they append a random query string parameter to each request.
So that is what I basically did to workaround the caching problem with the template files. I created a function called cacheBust() that just returned the current times milliseconds value and used that to generate my random query string. Here's some sample code:
function cacheBust() {return new Date().getMilliseconds().toString();}
function GetTimeEntries(day) {
// Show the loady
showLoady();
$.ajax({
type: "GET",
cache: false,
url: "/TimeEntry/" + day.replace(/\//g, "-"),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// This method loads the HTML template and
// prepares the container div to accept data.
$('#TimeWrapper').setTemplateURL('/scripts/timeentry.vw?_=' + cacheBust());
// This method applies the JSON array to the
// container's template and renders it.
$('#TimeWrapper').processTemplate(msg);
// Hide the loady.
hideLoady();
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
// typically only one of textStatus or errorThrown
// will have info, I'm not using either.
hideLoady();
$('#TimeWrapper').empty();
$('#TimeWrapper').append("<p class='errord'>There was a problem loading the data from the server. Sorry I got nothing else.</p>");
}
});
}
And now we get the most up to the second versions of our templates. Once I'm done with development it will be beneficial to have the templates be cached. I figure once that happens I'll change my cacheBust() function to return a constant (something like, "ItCompilesSoShipIt").
Now Playing: Snow Patrol - Open Your Eyes
Great...I ran into the same problem..really helpful solution...Thanks.
ReplyDelete+1, great!
ReplyDelete