"a place for my stuff..." -- a blog by John Nelson

 

 
 

Frankly, I’m surprised that it took until page 12 of the jQuery Cookbook to mention putting JavaScript at the bottom of the page before the closing </body> tag.  Pages load faster with the JavaScript at the bottom, and it removes the need to use the ready() function.  This is great advice.  Using a ContentPlaceHolder helps keep the scripts in their optimal location.

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
  <title>
    <asp:ContentPlaceHolder ID="TitleContent" runat="server" />
  </title>
</head>
<body>
  <div>
    <asp:ContentPlaceHolder ID="MainContent" runat="server" />
  </div>
  <script type="text/javascript"
    src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
  <!-- ScriptContent for putting JavaScript at the bottom of every page -->
  <asp:ContentPlaceHolder ID="ScriptContent" runat="server" />
</body>
</html>

Then, I’m able to include an <asp:Content> element inside of my View and use it freely.  Notice that I was able to include jquery.min.js above the ContentPlaceHolder, which means jQuery will already be warm for any JavaScript in my ScriptContent.

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
  About
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
  <h2>About</h2>
  <div class="about-message"></div>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="ScriptContent" runat="server">
  <script type="text/javascript">
    $('.about-message').text("This is the About Page!");
  </script>
</asp:Content>


Another added perk to this ContentPlaceHolder approach is that it lets me include other JavaScript libraries that individual Views might depend on.  Pretty simple, but I hope you enjoy it!

Thursday, January 21, 2010 10:00:41 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
ASP.NET MVC | JavaScript | jQuery
OpenID
Please login with either your OpenID above, or your details below.
Name
E-mail
(will show your gravatar icon)
Home page

Comment (Some html is allowed: a@href@title, b, blockquote@cite, i, strike, strong, sub, sup, u) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

Enter the code shown (prevents robots):

Live Comment Preview

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2010
John Nelson
Sign In
Statistics
Total Posts: 24
This Year: 2
This Month: 0
This Week: 0
Comments: 1
 
  All Content © 2010, John Nelson