title: JavaScript not working on external file
body: <p>When I use this code inside my HTML document it's working:</p>
  
  <pre><code>$('a.tocenter[href*=#]').click( function() {
      if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
      &amp;&amp; location.hostname == this.hostname) {
      var $target = $(this.hash);
      $target = $target.length &amp;&amp; $target || $('[name=' + this.hash.slice(1) +']');
      if ($target.length) {
      var targetOffset = $target.offset().top;
      $('html,body').animate({ scrollTop: targetOffset - ( $(window).height() - $target.outerHeight(true) ) / 2 }, 1000);
      return false;}
      }
  });
  </code></pre>
  
  <p>If I try to put this code inside an external JavaScript file and then link it with:</p>
  
  <pre><code>&lt;script src="js/main.js"&gt;&lt;/script&gt;
  </code></pre>
  
  <p>It's not working, to let it work I had to wrap it inside:</p>
  
  <pre><code>$( window ).load(function() {
      ...
  });
  </code></pre>
  
  <p>If I do this it works.</p>
  
  <p>I'm a total newbie in JavaScript/jQuery, is this normal or am I doing something wrong? Why is it behaving like that? Is it a good practice to do that? </p>
  
  <p>The only purpose of having it in an external file is for keeping the code clean and understandable.</p>