title: Encapsulate javascript for an embedded widget
body: <p>I have a javascript file that users can embed on their site.  It uses coffeescript and the Rails asset pipeline to compile a bunch of files into one.</p>
  
  <pre><code># The following dependencies will be compiled into test.js (rails asset pipeline manifest file)
  #
  #= require jquery
  #= require jquery.cookie
  
  jQuery -&gt;
    $.cookie('foo', 'bar')
    console.log $.cookie('foo')
  </code></pre>
  
  <p>This works as expected with a sample page:</p>
  
  <pre><code>&lt;!DOCTYPE html&gt;
    &lt;head&gt;&lt;/head&gt;
    &lt;body&gt;
      &lt;script src="http://localhost:3000/assets/test.js" type="text/javascript"&gt;&lt;/script&gt;
    &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>But this script is a widget so it should be embeddable on any site.  If the user adds their own jquery below it, then things break:</p>
  
  <pre><code>&lt;!DOCTYPE html&gt;
    &lt;head&gt;&lt;/head&gt;
    &lt;body&gt;
      &lt;script src="http://localhost:3000/assets/test.js" type="text/javascript"&gt;&lt;/script&gt;
      &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"&gt;&lt;/script&gt;
    &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>This gives the error <code>Uncaught TypeError: Object function (a,b){return new e.fn.init(a,b,h)} has no method 'cookie'</code></p>
  
  <p>What is the best way to wrap up everything in test.js so is self contained?  I thought coffeescript wrapping everything in an anonymous function might help here but I guess not.</p>
  
  <p>Thanks!</p>