Wednesday, October 20, 2010

SparkViewEngine Easy CSS and Javascript Versioning

One of the challenges you face with web development is that whenever changes are made to CSS or Javascript files your browser will have an out of date version already cached. There are many articles on this subject, but I’m going to show you how clean this can be when using the SparkViewEngine.

Our goal is to prevent the browser from using the old cached version and to make versioning of our files automatic without having to manage things with each release. We can accomplish this for example by turning what gets rendered to the browser to include a query string like v=1.0 as an example.

Enter Spark Bindings

Spark bindings are documented well here. In summary they allow the ability to create your own tags and have the template engine interpret them with your own custom code as well as intercept existing tags adding additional behavior. This gives us a great opportunity to just intercept the standard tags and add the version query string. This way during development there are no funky ways to make the stars align in order for the site to behave properly.

So in our view.

In our Bindings.xml that the SparkViewEngine uses to determine the custom behavior.

The extensions to intercept and add the version query string.

You also see that it is another good way to determine whether or not to use the minified version of files as well. For your own scenarios you might want to consider that you might not want to version your jQuery files, but instead change the url to one that is located on a CDN. In my opinion it can't get much less intrusive than that!

Do you have any other ideas where this might be useful?