After working several years with the Castle Monorail MVC framework, I decided to try ASP.NET MVC to see if it had caught up to Monorail. The transition seemed to go rather smoothly, but one area where I was surprised to find how clumsily it was handled, was the management of JavaScript files. Basically, if some part of a page, say a helper or partial page, needed a particular JS file, you had one of two choices.

The first option is to have the part itself write the script tag. This allows the part to operate as a “black box” – just drop it in and it works – But it means that there will be script tags loading files scattered throughout the page, and that the part needs to know your folder structure where you keep your JavaScript files. And it needs to know if you want the file loaded from your website or from a CDS like Googleapi.com. And, since there’s a good chance it will depend on jQuery, you have to make sure that jquery.js is loaded first, at the top of the page, despite “best practices” which say script files should be loaded at the bottom of the page. Then, let’s say, two different partial views on the same page use the same JS file, you need a way of making sure it’s only included once. Plus, there’s a good chance it will also depend on its own CSS file being loaded, which doubles the problems above. As a way to address this, Microsoft (well, PluralSite’s training videos on Microsoft’s site) recommends putting the script tags in a @section named Scripts, and rendering that in the layout, which helps but only addresses some of these problems.

Alternately, you can break the black box, and manually add the needed script & CSS link tags in your layout. This allows you to group the files tag together in the proper places, CSS at the top, JS at the bottom. But, you must know all the JS files all components of the page need, including all dependencies they have. And if you are putting these in a layout file, then you’ll need to put all the JS files needed for all pages anywhere on the site.

Wouldn’t it be great if there was a way to automatically figure out just the files we need for a certain page, and include just those, without us having to do a lot of thinking about it. Isn't that the type of thing we invented computers for?

Monorail also lacked such a manager, but Monorail has neither the major corporate sponsor nor the large user community base of ASP.NET MVC, where I figured someone would have written one. I wrote a manager like this for Monorail, so I guess that someone is going to be me… which leads us to the JavascriptHelper.

Usage

Last edited Jul 20, 2012 at 4:34 PM by JamesCurran, version 2

Comments

No comments yet.