title: Load Javascript after page content is loaded with Ajax
body: <p>I am using Ajax (and jQuery, and also CoffeeScript) to load pages in a new web-site I am creating. For the navigation menu I then use the jQuery function <a href="http://api.jquery.com/load/" rel="nofollow"><code>load</code></a> to load only one part of the page (namely, the content) like this (from <code>/page1</code>):</p>
  
  <pre class="lang-js prettyprint-override"><code>$( 'a' ).click -&gt;
    $( '#container' ).load '/page2 #content'
  
    false
  </code></pre>
  
  <p>The problem with this is that I have JavaScript code in <code>page1</code> (or, more correctly, in a template file) that is global on the site (due to the asset pipeline as I am using Rails 3.1). This code binds some actions to events (is this the correct jargon?) in DOM elements that are located in <code>page2</code>. But, as this script is run in the page that is first loaded (which easily could be <code>page1</code>), then the script that binds these actions to the elements will be executed in <code>page1</code>, and thus the DOM elements that they actually <em>should</em> be bound to (in <code>page2</code>) will not be touched.</p>
  
  <p>Now, I know some ways I can fix this, but I don't like neither of them. One of these would be to put this action/event binding into a function, and then call this method after loading <code>page2</code> with Ajax, but this would require me to either have introduce a special case in my page loading logic where I load the binding function after page load to bind the elements, or to have a script in the <code>page2</code> content where I call the function.</p>
  
  <p>I would rather not go with the former approach, as I have a more general way of loading pages (by using the <code>&lt;a&gt;</code> tag's <code>href</code> attribute), and introducing special cases on page load just uglifies it all. The latter solution is a rather nicer one I believe, but I would hate to put <code>&lt;script&gt;</code>tags into the content of the page that I am retrieving. I like separating content from behaviour and all that, and I feel that this might be mixing it all up a bit.</p>
  
  <p>So, what I really want to know here is whatever would be a good way to solve this problem. If anyone out there knows how to go about doing this, then I would welcome any suggestions.</p>