title: How to embed Javascript widget that depends on jQuery into an unknown environment
body: <p>I'm developing a javascript widget that depends on jQuery.  The widget may or may not be loaded onto a page that already has jQuery loaded.  There are many problems that come up in this case...</p>
  
  <ol>
  <li><p>If the web page does not have jQuery, I must load my own jQuery.  There seems to be a delicate timing issue when doing this, however.  For example, if my widget loads and executes before jQuery is finished loading and executing, I get a <code>jQuery is not defined</code> error.</p></li>
  <li><p>If the web page does have jQuery, I can usually work with it.  If the jQuery version is old, however, I would like to load my own.  If I do load my own, however, I need to do it in such a way as to not stomp on their <code>$</code> variable.  If I set <code>jQuery.noConflict()</code> and any of their scripts depend on <code>$</code>, then I have just broken their page.</p></li>
  <li><p>If the web page uses another javascript library (e.g. prototype), I needed to be sensitive of prototype's <code>$</code> variable also.</p></li>
  </ol>
  
  <p>Because of all of the above, it is seeming easier to not depend on jQuery.  But before I go down that road, which will involve mostly rewriting my widget code, I wanted to ask for advice first.</p>
  
  <p>The basic skeleton of my code, including the timing bug and sometimes <code>$</code> bugs, follows:</p>
  
  <pre><code>&lt;script type="text/javascript" charset="utf-8"&gt;
  // &lt;![CDATA
   if (typeof jQuery === 'undefined') {
    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = '{{ URL }}/jquery.js';
    head.appendChild(script);
   }
  // ]]&gt;
  &lt;/script&gt;
  &lt;script type="text/javascript" src="{{ URL }}/widget.js"&gt;&lt;/script&gt;
  </code></pre>
  
  <p>My widget has the following structure:</p>
  
  <pre><code>(function($) {
   var mywidget = {
    init: function() {
     ...
    }
   };
   $(document).ready(function() {
     mywidget.init();
   });
  })(jQuery);
  </code></pre>
  
  <p>If there are any pointers or resources for achieving a widget that can work in all the mentioned environments, they would be greatly appreciated.</p>