views:

432

answers:

5

I prefer the use of external css and javascript files. There are however many cases where the content of a javascript or css file needs to be dynamic. I'll usually just transfer the javascript or css to inline or inpage code in my aspx page and handle the dynamic stuff there.

Does anyone have a better approach? Would there be a way to generate entire js or css files using asp.net's regular templating language?

I'm currently using webforms but I'd be interested in solving this issue in MVC as well.

Thanks

+3  A: 

I've used a HTTPHandler to send back dynamic javascript before. But not something that inherits from System.Web.UI.Page.

Using a HTTPHandler and an ASHX or AXD is the "ASP.Net" way to send back resources dynamically.

Tom Ritter
As far as I am aware, the AXD is for embedded static resources or to combine scripts. I agree with the ashx, since it is what I have used (also custom handler classes).
eglasius
I'm not sure about "Best Practices" but we routinely map .axd url's to HTTPHandlers in the backend. Although yes, .axd is also the extension for embedded resources.
Tom Ritter
+1  A: 

I have used handlers for dynamic css. Depending on what you need, you can do the same for js files.

I had a css file with placeholders for the pieces that needed to be dynamic like ##bacgroundcolor##, and the handler just replaced as appropriate.

I have also used an approach where I use css classes to mark html elements that need special behaviors. Then the static js, looks for this elements and hook the appropriate handlers. This is something that certainly would be even easier with jquery (I did it with regular js back then :().

eglasius
A: 

I've done this in an aspx page before, but in my opinion the WebForm style doesn't suit itself well to rendering strictly javascript or CSS. Every time I've done it, the page has ended up looking quite a bit like classic ASP.

Ryan Brunner
First you minimize what you will be sending, by moving static pieces to regular files and leaving only the dynamic stuff. Also, you can use a file as a template with placeholders.
eglasius
A: 

hopefully the actual JavaScript you are using would stay static and you would just pass parameters to the JavaScript methods.

Aaron Hoffman
Generally this is so but sometimes it's just so much easier to make it dynamic. This is especially true when you consider the complexity of the webforms page event model.
Mr Grieves
A: 

I have taken JavaScript code that had been in the markup of a page and containing things like <%= control.ClientID %> and replaced it with static JavaScript. I refactored the code into a class, I then refactored these variable parts into class members. The page creates an instance of the class, with things like ClientID set. The functions can then be static.

John Saunders