title: The effective way to call javascript initializing form?
body: <p>One often have form with some dynamic parts, that needs to be initialized onload. E.g. datepickers, enhanced selects, section toggling, hiding/showing conditional elements etc. </p>
  
  <p>Example:</p>
  
  <pre><code>&lt;form&gt;
      &lt;input type="text" name="date"&gt;
      &lt;select name="selection"&gt;&lt;/select&gt;
  &lt;/form&gt;
  </code></pre>
  
  <p>and I want to init datepicker on the date element and Select2 on the selection element.</p>
  
  <p>Where to put the form initialization?</p>
  
  <p>My thoughts: </p>
  
  <ul>
  <li><p>Init throught global selector:</p>
  
  <pre><code>$(function() {
      $('input[name=date]').datepicker();
      $('select[name=selection]').select2(); 
  })`. 
  </code></pre>
  
  <p>But I have one js file for the whole web, so this would led to crawling the whole DOM on each page load, even if the element is not present on current page. </p></li>
  <li>Some kind of conditional selector. E.g. give <code>&lt;body&gt;</code> and id and add to my global js file something like this: <code>$(function() { $('input[name=date]', 'body#foo').datepicker(); })</code></li>
  <li><p>Encapsulate the init for each form into a function (or class method), and call the function from HTML:</p>
  
  <pre><code>&lt;script type="text/javascript"&gt;
      $(document).ready(initMyForm());
  &lt;/script&gt;
  </code></pre></li>
  </ul>
  
  <p>But I'm guessing, isn't there any better way? What would you suggest, especially for bigger projects with many different forms requiring different javascript initialization?</p>