简体   繁体   中英

How to organize front end JavaScript code in ASP.NET MVC project?

I have a ASP.NET MVC project which adopts lots of JavaScript (jQuery and d3). I am new to web development, so I want to ask for some help on how to organize front end script code.

My current way is, each folder under 'Views', has only one corresponding .js file (which means all partial views (.cshtml) under that folder, share that .js file), and I explicitly initialize all .js files of my project in $(document).ready() of _Layout.cshtml.

This introduces 2 issues:

  1. Because all partial views puts there codes in one .js file, so it makes each .js file huge and complex.
  2. Because I hardcoded initialize all .js files when _Layout.cshtml is loaded, so even when one view is not loaded, its behind .js is executed, sounds not flexible.

So here are my questions:

  1. How to make each partial view has its own .js file (split current .js into small pieces).
  2. How can I load and run a partial view's .js file only when that partial view is loaded.
  3. If I use TypeScript and KnockoutJS, do they provide any benefits on organizing front end script code?

Thanks in advance.

Split up your javascript code into multiple file such that each js file corresponds to the partial views.

Then load the corresponding js in partial view in partial view instead _Layout.cshtml file. In this way, the corresponding js will execute only when the partial view is loaded.

TypeScript is a class-based object-oriented programming style applied to basic javascript, which is developed and maintained by Microsoft. This does not help to organized the files but do help to maintain the js code in an OOP style.(link here )

KnockoutJS is Model-View-ViewModel(MVVM) pattern applied to javascript. You can modularized each js files in KnockoutJS, ie, separate js for Model, View and ViewModel but they will have dependency each other.(see documentaion )

There are multiple ways to skin a cat. If you have javascript code specific to a partial view it's entirely fine to just skip the step of including a file and embedding JavaScript directly in there by means of the <script> tag. This solves problem 1 and 2 you posted because razor partial views boil down to just arbitrary HTML inserted into the DOM when they are loaded.

As for TypeScript and KnockoutJS the benefits they provide are highly subjective to yourself and the project you are working on. I would suggest reading up on the features they provide and see if that's an avenue you want to pursue -- There is no right or wrong answer to this, at least not with a lot of specific context as to what you're working on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM