Adventures of a wannabe geek!

Ranting within

Using Razor to Clean Up My Scripts and Styles

Today I witnessed a real show of power of the Razor View engine included with ASP.NET MVC3.

Traditionally in sites scripts and styles are all thrown in the masterpage (webforms) or sitelayout (razor). This can lead to pages taking potentially longer to load when they don’t even need some of the scripts or styles. As Google announced that page load times were going to be part of Google rankings, it’s not ideal for this to happen.


This has been made easier as Razor has introduced the ability to define sections in our pages.


The code here checks to see if a section of the required name is defined and if so it will render it.  This can be used to encapsulate scripts and styles as shown. Here we load the site.css as this is required for the entire site and we load the jQuery main library as this will also be required all over the site. We can then define Sections in our sitelayout and render specific scripts and styles required for a specific View


This image shows that by then using the appropriate section named from the sitelayout page that we can play only the scripts required for that view in that section. This will help to make the views as lightweight as possible when they are being rendered.

This is a demonstration of the power of the Razor view engine. It just makes it very easy to achieve. I’m loving using MVC3 and feel as though things are not quite “right” when I go back to working on webforms projects! :(

Hope it helps!