nologo
nologo

Reputation: 6278

structuring javascript in an .net MVC application

I’m looking for some guidance on structuring JS code in an .net MVC application. I have JavaScript at the bottom of each page which is loaded, I want to apply a name-spacing / modular pattern to my JavaScript, removing it from inline code to separate JS files and load them on demand based on what page is being accessed.

When I google around, I tend to only find MVC patterns for javascript (this for example http://addyosmani.com/largescalejavascript/) which is great but I’m struggling to understand how I can implement this into an MVC application.

Any advice is welcome.

thanks

Upvotes: 3

Views: 839

Answers (1)

redsquare
redsquare

Reputation: 78667

I use a technique that is similar to the one described here by Paul Irish. However rather than using hardcoded id's or classname's in order to know what scripts need loading and initialising I use the urls that are requested (full requests and ajax reqs)

For instance say I have a customer edit view that is served in response to a request to a url like myapp\customer\12\edit I would have a customer namespace in my js that had an inner edit namespace.

The customer namespace would have an init func likewise the edit. All customer pages when loaded would invoke the customer init event then any action level namespace if it exists. This would have an init func that would be auto called when the page was loaded (I have some magic that parses the url so that we know which js to initialise). So parsing the url would first invoke the customer init fund then the customer.edit init func. There is also common init functions that get fired everytime for app wide logic (to create a sidebar page widget for example).

I do not load the js on demand. I find it is better from a latency point of view to combine+minify all js files and serve them under gzip obviously.

Upvotes: 2

Related Questions