title: How should javascript in an ajax loaded partial view be handled?
body: <p>In ASP.NET MVC, what is the preferred pattern for running Javascript on a partial view that is loaded via Ajax?</p>
  
  <p>For example, suppose you need to wire up some click events in your partial view.</p>
  
  <p>Of course, putting something like this in the partial view would not work, because the document ready event won't fire after the partial view is Ajax loaded.</p>
  
  <pre><code>&lt;script type="text/javascript"&gt;
      $(function() {
          $("a.foo").click(function() {
              foo();
              return false;
          });
      });
  &lt;/script&gt;
  </code></pre>
  
  <p>I suppose something like this might work, but is it safe?</p>
  
  <pre><code>&lt;script type="text/javascript"&gt;
      $("a.foo").click(function() {
          foo();
          return false;
      });
  &lt;/script&gt;
  </code></pre>
  
  <p>The pattern I have been using has been to run any Javascript from my parent view after loading the partial, like this:</p>
  
  <pre><code>$.get(url, function(html) {
      $("#partialDiv").html(html);
  
      // Now that the partial has loaded...
      RegisterClicks();
  });
  </code></pre>
  
  <p>But I've been working through <a href="http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/" rel="nofollow">this</a> example, and noticed that they simply put their click registering code inline in the partial view.</p>
  
  <p>Is this a generally safe pattern to adopt?  How can I be sure that the DOM for the partial view has finished loading before my script runs?</p>