Hemant
Hemant

Reputation: 19826

Where to place jQuery code in ASP.NET MVC view page?

I have just started to learn jQuery + ASP.NET MVC. Whatever tutorials I have read about jQuery, they suggest that all jQuery code should be in head element.

Now in the ASP.NET MVC project, I have one master page which is responsible for head element. In other view pages, I get content place holder which draws in body element.

I am confused now. Should I ignore the advice of keeping jQuery in head element or there is some way to write different jQuery code in each view page?

Upvotes: 4

Views: 1430

Answers (4)

lomaxx
lomaxx

Reputation: 115763

I'd put them externally and use the <script type="text/javascript" src='<%= Url.Content(~/scriptlocation) %> /> method to reference them

Upvotes: 0

Svante Svenson
Svante Svenson

Reputation: 12488

  • Refactor common stuff to jQuery plugins
  • Put related things together and unrelated things in their own js-files
  • Run jslint on all js-files you've written
  • Have a bunch of <script src=...-tags during development (in your master)
  • Before deploying to test server, minify and concatinate all js-files into a big one, so that it gets cached and you don't get that many http calls.
  • If one of your js-files is huge and only needed for a specific page, exclude just that file from the big one.

Upvotes: 2

redsquare
redsquare

Reputation: 78667

Keep your js in external .js files. That way they get cached.

Upvotes: 9

Chris James
Chris James

Reputation: 11701

You can include more content place holders in your master page, which your content pages can then fill with thier own JQuery

So in the head of your master page make something like:

<asp:ContentPlaceHolder ID="Javascript" runat="server" />

Then in your view pages

<asp:Content ID="Content1" ContentPlaceHolderID="Javsacript" runat="server">
    //js here
</asp:Content>

That said, you should maybe consider including your javsascript in seperate JS files and include them, to seperate your concerns a bit.

Upvotes: 8

Related Questions