title: Avoiding global context in jQuery used on all pages of a CMS
body: <p>I work with a proprietary CMS every day, and one of the easiest ways to customize individual sites is with the theme.js that is present on all pages. The preferred approach is usually jQuery, but vanilla javascript is also encouraged. In a sense, think of it as being like the functions file in Wordpress. It's not a perfect solution, and more it just tacked on to do new things, but it's what it is.</p>
  
  <p>When I add isolated functions, things that aren't called but just act when the page loads, I want to add them in a way that's more standards compliant and less prone to bugs. One thing I want to avoid is blatant global context(s).</p>
  
  <p>Example of how I was shown to do it at first:</p>
  
  <pre><code>$(function() {
  
      $('div.target').append('&lt;p&gt;New stuff&lt;/p&gt;');
  
  });
  </code></pre>
  
  <p>We talked it over, and it was agreed to encapsulate:</p>
  
  <pre><code>(function() {
      var foo;
      if (bar) {
          // some code
      }
  }());
  </code></pre>
  
  <p>Problem is, when I run the code exactly like that, it doesn't take effect.
  So, I changed it to this:</p>
  
  <pre><code>(function($) {
  
      $(document).ready(function() {
  
          $('div.target').append('&lt;p&gt;New stuff&lt;/p&gt;');
  
      });
  
  }(jQuery));
  </code></pre>
  
  <p>That works, but I don't want it to defeat the purpose. Is adding <code>$(document).ready(function()</code> back peddling our endeavor to encapsulate and avoid global context with small functions?</p>