62

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...

  1. 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 jQuery is not defined error.

  2. 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 $ variable. If I set jQuery.noConflict() and any of their scripts depend on $, then I have just broken their page.

  3. If the web page uses another javascript library (e.g. prototype), I needed to be sensitive of prototype's $ variable also.

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.

The basic skeleton of my code, including the timing bug and sometimes $ bugs, follows:

<script type="text/javascript" charset="utf-8">
// <![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);
 }
// ]]>
</script>
<script type="text/javascript" src="{{ URL }}/widget.js"></script>

My widget has the following structure:

(function($) {
 var mywidget = {
  init: function() {
   ...
  }
 };
 $(document).ready(function() {
   mywidget.init();
 });
})(jQuery);

If there are any pointers or resources for achieving a widget that can work in all the mentioned environments, they would be greatly appreciated.

robhudson
  • 2,658
  • 1
  • 21
  • 19

7 Answers7

98

After reviewing some answers and pointers, and finding some helpful jQuery hackers, I ended up with something like the following:

(function(window, document, version, callback) {
    var j, d;
    var loaded = false;
    if (!(j = window.jQuery) || version > j.fn.jquery || callback(j, loaded)) {
        var script = document.createElement("script");
        script.type = "text/javascript";
        script.src = "/media/jquery.js";
        script.onload = script.onreadystatechange = function() {
            if (!loaded && (!(d = this.readyState) || d == "loaded" || d == "complete")) {
                callback((j = window.jQuery).noConflict(1), loaded = true);
                j(script).remove();
            }
        };
        (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script);
    }
})(window, document, "1.3", function($, jquery_loaded) {
    // Widget code here
});

This will load jQuery if it's not already loaded and encapsulates it in the callback so it doesn't conflict with a pre-existing jQuery on the page. It also checks that a minimum version is available or else loads a known version -- in this case, v1.3. It sends a boolean value to the callback (my widget) on whether or not jQuery was loaded in case there are any triggers needed to be made. And only after jQuery is loaded does it call my widget, passing jQuery into it.

gerry3
  • 21,420
  • 9
  • 66
  • 74
robhudson
  • 2,658
  • 1
  • 21
  • 19
  • 2
    Doesn't get much better than that, wish I could give more points! – Mark G. Jul 18 '11 at 20:48
  • I've done something very similar to this. I'd really appreciate if you can help to fix the issue http://stackoverflow.com/questions/7817522/uncaught-typeerror-can-not-set-propery-function-name-of-undefined-for-widget/ – Bongs Oct 19 '11 at 10:27
  • 1
    Here is a coffeescript version I adapted: https://gist.github.com/4361800 Thanks for the great solution! Btw, off topic, but I don't really understand that `(window, document, "1.3", function($, jquery_loaded) {` syntax where it's tacked on the end of the function. Where can I read more about that? – Brian Armstrong Dec 22 '12 at 23:25
  • 3
    Was seeing a `HIERARCHY_REQUEST_ERR: DOM Exception 3` error with this when it was run on badly formed html (blank line at the top of the file). Replacing `document.documentElement.childNodes[0].appendChild(script)` with `(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);` from below seemed to work better. – Brian Armstrong Dec 23 '12 at 07:12
  • Thanks @BrianArmstrong, I also ran into that issue when the HTML started with a comment. Your solution seems more robust. – mrooney Jun 17 '13 at 18:19
  • 1
    I don't think your string version comparison is valid for 1.10 and above unfortunately. – toxaq Apr 26 '14 at 23:51
  • does it make sense to `return jquery_loaded` in the callback? since if a proper jQuery version already exists and the callback happens to return truthy you'd be loading jQuery a 2nd time... – Joe B Jun 07 '14 at 17:23
  • I know this is a old topic, but how can I load a second script jquery dependant after that load ? It says that $ is not a function because the second script is not in the callback scope; thanks – iguypouf Jun 27 '20 at 07:35
5

See How to build a web widget (using jQuery) by Alex Marandon.

(function() {

// Localize jQuery variable
var jQuery;

/******** Load jQuery if not present *********/
if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.4.2') {
    var script_tag = document.createElement('script');
    script_tag.setAttribute("type","text/javascript");
    script_tag.setAttribute("src",
        "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js");
    if (script_tag.readyState) {
      script_tag.onreadystatechange = function () { // For old versions of IE
          if (this.readyState == 'complete' || this.readyState == 'loaded') {
              scriptLoadHandler();
          }
      };
    } else { // Other browsers
      script_tag.onload = scriptLoadHandler;
    }
    // Try to find the head, otherwise default to the documentElement
    (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
} else {
    // The jQuery version on the window is the one we want to use
    jQuery = window.jQuery;
    main();
}

/******** Called once jQuery has loaded ******/
function scriptLoadHandler() {
    // Restore $ and window.jQuery to their previous values and store the
    // new jQuery in our local jQuery variable
    jQuery = window.jQuery.noConflict(true);
    // Call our main function
    main(); 
}

/******** Our main function ********/
function main() { 
    jQuery(document).ready(function($) { 
        // We can use jQuery 1.4.2 here
    });
}

})(); // We call our anonymous function immediately
Pavel Chuchuva
  • 22,633
  • 10
  • 99
  • 115
2

What if you also want to use some jQuery plugins? Is it safe to make yourself a single file with the minified versions of the plugins, and also load those, as below? (Loaded from S3, in this particular example.)

(function(window, document, version, callback) {
  var j, d;
  var loaded = false;
  if (!(j = window.jQuery) || version > j.fn.jquery || callback(j, loaded)) {
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js";
    script.onload = script.onreadystatechange = function() {
        if (!loaded && (!(d = this.readyState) || d == "loaded" || d == "complete")) {
            window.jQuery.getScript('http://mydomain.s3.amazonaws.com/assets/jquery-plugins.js', function() {
              callback((j = window.jQuery).noConflict(1), loaded = true);
              j(script).remove();
            });
        }
    };
    document.documentElement.childNodes[0].appendChild(script)
  }
})(window, document, "1.5.2", function($, jquery_loaded) {
  // widget code goes here
});
cailinanne
  • 8,332
  • 5
  • 41
  • 49
  • I'm trying to do something very similar to this. Can you help me fix the issue http://stackoverflow.com/questions/7817522/uncaught-typeerror-can-not-set-propery-function-name-of-undefined-for-widget/ – Bongs Oct 19 '11 at 10:25
1

SEE Can I use multiple versions of jQuery on the same page?

Community
  • 1
  • 1
micahwittman
  • 12,356
  • 2
  • 32
  • 37
1

Can you use document.write() to optionally add the jQuery script to the page? That should force jQuery to load synchronously. Try this:

<script type="text/javascript" charset="utf-8">
// <![CDATA
 if (typeof jQuery === 'undefined') {
  document.write('<script src="{{ URL }}/jquery.js"><' + '/script>');
 }
// ]]>
</script>
<script type="text/javascript" src="{{ URL }}/widget.js"></script>

If you want to do the jQuery check inside your widget script then I believe the following works cross-browser:

(function() {
 function your_call($) {
  // your widget code goes here
 }
 if (typeof jQuery !== 'undefined') your_call(jQuery);
 else {
  var head = document.getElementsByTagName('head')[0];
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = '{{ URL }}/jquery.js';
  var onload = function() {
   if (!script.readyState || script.readyState === "complete") your_call(jQuery);
  }
  if ("onreadystatechange" in script) script.onreadystatechange = onload;
  else script.onload = onload;
  head.appendChild(script);
 }
})()
Sean Hogan
  • 2,902
  • 24
  • 22
  • I actually ended up with something very similar which I will try to post as another answer (since I'm limited to number of characters in a comment). – robhudson Feb 01 '10 at 04:36
0

I know this is an old topic... but i got something faster that your hack. Try in your widget

"init": function()

that will fix the trouble

-1

I would download the jQuery source and modify the jQuery object to another (jQueryCustom).

And then find the instance that sets the $ symbol as a jQuery object and comment that routine.

I don't know how easy or difficult could that be, but I'd sure give it a try.

(Also, check your second option, as it is not bad, the site where the widget will be executing, might have a jQuery version older than the one you need).

EDIT: I just checked the source. You just have to replace jQuery with another string (jQcustom for example). Then, try commenting this line:

_$ = window.$

And you make reference to the custom jQuery like this:

jQcustom("#id").attr(...)
metrobalderas
  • 5,180
  • 7
  • 40
  • 47