开发者

Keeping jquery/javascript separate from asp.net MVC views?

I am trying to found it the best way to keep my scripting i.e. j开发者_高级运维query/javascript separate from my view (html) in asp.net MVC...

Does anyone have any idea the best way of doing this??

I am seeing alot of code smell in my views ...

I have used in the past JavascriptMVC which does a really good job and maybe its a good idea to combine them but considering i won't be using the view part of the javascriptmvc maybe its not the right direction to take..

I would really love some ideas and help on the best way of keeping scripting away from views etc..

I am using a number of external modules like YUI and jquery so if i need to employ another concept/layer - i don't see a problem

Look forward to any help

Thanksa


We may (or may not) have a philosophical difference in how separate to keep javascript from mark up. In my opinion, it's ok to have javascript on the page as long as its not embedded in the markup itself. If possible, it should be off in it's own files but when it directly references view-specific elements, I prefer to have it in the view file itself.

Here's the strategy that I use.

  1. Refactor common code to plugins. Put plugins in a separate JS file and include them where needed.
  2. Use a separate ContentPlaceHolder (CPH) for script includes and code just inside the closing body tag in the master page. This keeps the JS functionally separate on the page and ensures that it is loaded at the bottom of the page.
  3. Put common JS includes just above the script CPH in the master page.
  4. Put code common to every page, but containing page-specific references after the common includes in the master page.
  5. Avoid putting JS in partial views by using live handlers, etc. where possible.
  6. Wrap all code, except includes and function definitions, inside $(function() { } (document ready).
  7. Use content-distribution network (CDN) versions of common code where possible.


It will be easier to help you if you paste a code snippet of your existing code in the question. Look at this blog post to see how you can separate your javascript from your html.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜