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.

image

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

image

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

image

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!

Comments (2) -

Terry Brown
Terry Brown
3/21/2011 8:06:44 AM #

hey Paul,

I'm unfortunately stuck with webforms at the moment, though just wanted to say the above is very possible with webforms too.

In our masterpage we define:

<asp:ContentPlaceHolder id="Scripts" runat="server" />

in the head of the master page document and then in any child pages we can just consume that (though naturally, as with Razor and the second parameter on @RenderSection, it's optional:

<asp:Content id="Scripts" ContentPlaceHolderId="Scripts" runat="server">
    .... your scripts here ....
</asp:Content>


I admit, nowhere near as elegant, though functionally does all that the Razor sections do.

Hope that helps Smile
Cheers,
Terry

redsquare
redsquare
3/21/2011 2:36:59 PM #

What about resource minification + combining?

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading

About Me

 

Web Developer. My most used framework is C# with MVC but use Webforms on occasion. Im an advocate of clean, maintainable code and am very passionate for what I do. Absolutely obsessed with Continuous Integration and how it should be used in every day development scenarios. Trying to move towards a system of Continuous Deployment
Follow Me on Twitter

Jetbrains Academy Member

 

MVB Blogger

 

Friends Of Redgate

Month List