开发者

In an ASP.NET MVC site, where would the JQuery code go?

I'm just getting started with ASP.NET MVC. I'm going to be using JQuery on the website I'm making, but I'm not really sure about one thing: where would JQuery code be placed?

This concerns two things:

  • Where do I import the JQuery JavaScript file? 开发者_C百科(I've been thinking that the Master page would be a good place to do this; am I right, or do I have to import it in each view?)
  • Should all my JQuery code be referenced from the Master page (i.e., I store my code that uses JQuery in a separate .js file and reference it in a <script> tag)?

Thanks in advance.


Anything that you will use in every page put a import in your master. If its something that you will only use on a smaller scale, put the import in the view that will use it.

The key is to not load unnecessary bytes when they won't even be used. I have a universal js file that contains anything that will be used as more common functions across the board imported in my master. Then on a page by page basis, I have only the js imports that I need for that page.

If you put every js import in your master that means it will load that js on every page, when maybe half of them aren't even used for that particular page. That can have a big impact on page load times.

I suggest also using something that can compress the js to a minified version for production. Telerik has their Script Registrar and it's a really nice tool as well.


Add JQuery to the bottom of Site.Master just about the body tag. This means the page will load and not wait for the Javascript.

But the JQuery relevant to each view, but add on a View level.


  • You should import your JQuery library on the master page. Probably you'll use JQuery on most of the views so having the reference in only one place it's most welcome.
  • Normally it's a good practice to have all javascript code you can in separated files, as less inline javascript as you have the better. 2 reasons: more readable code and better performance since external javascript files are cached.


My jquery code is placed in the head of the masterpage since it's used on just about every view on the site. The only reason you wouldn't do this is if you're only using the jquery library on a few of your views, in which case there's no reason to load it up for every user.


You should let Google host jQuery for you.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜