Optimal script/stylesheet locations

Many people smarter than myself have written about best practices for where you include your stylesheets and scripts on a page. I won't duplicate that info here (for some good reading, see here or here. However, to summarize, its best for stylesheets to be placed in the header of your page, and its best for scripts to be included as close to the bottom of your page as possible. Assman facilitates that by decoupling the act of indicating a View/Partial requires a script or stylesheet, and the act of actually rendering those scripts and stylesheets on the page. The HtmlHelper extension method to indicate a View requires a resource is Html.RequireScript and Html.RequireStylesheet respectively. It is expected that you will call these methods from most of your views/partials. The HtmlHelper method to actually render the script and stylesheet includes to <script> and <link> tags, is Html.RenderScripts and Html.RenderStylesheets respectively. It is expected that calls to these methods will typically live in your master page/layout.

Named script and stylesheet registries

When you call RequireScript or RequireStylesheet, the resource is added to a script or stylesheet registry respectively. Scripts and Stylesheets each have a "default" registry. You can, however, specify a named registry when you call the RequireScript or RequireStylesheet methods. If you do that, it will be added to that special named registry instead. To render the scripts or stylesheets from a named registry, simply pass the name as a parameter to the RenderScripts or RenderStylesheets. If you add the same script or stylesheet to multiple registries, the first one to render wins (should be the one higher up on the page). Each script/stylesheet will only be included on a page once, even if you register them to multiple registries.

Last edited Jun 3, 2011 at 4:15 AM by andyalm, version 2


No comments yet.