Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't jQuery UI see jQuery?

I've built a JavaScript widget that must be embeddable on any third-party site, in any environment. The widget relies on jQuery and jQuery UI. I followed the steps in How to embed Javascript widget that depends on jQuery into an unknown environment to add jQuery in a responsible manner -- works great for embedding jQuery. But when I try to add jQuery UI, it fails. Here's the code:

(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 = "https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.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.documentElement.childNodes[0].appendChild(script)
  }
})(window, document, "1.3.2", function($, jquery_loaded) {
    $.getScript('http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.js', function(){
      console.log('loaded');
    });
});

When I run this, I get the 'loaded' mesage, followed by an error saying that "$ is undefined" on line 15 of jquery-ui.js. But how can $ be undefined when I'm using $.getScript() to load jQuery UI? And why do I see the message 'loaded' before I get the error? According to the jQuery documentation, getScript shouldn't execute the callback until the script has been loaded and executed.

Is there any way I can use this framework to include jQuery UI, or do I need to use a script loader like RequireJS in order to load everything, enforce dependencies, etc.?

like image 438
venutip Avatar asked Dec 13 '10 04:12

venutip


1 Answers

By calling .noConflict(1), the same as .noConflict(true), you're deleting jQuery, just remove the 1. The true argument to .noConflict() tells jQuery to remove not only $, but window.jQuery, which jQuery UI is trying to use afterwards, when it loads.

You can test it here, see there are no errors in the console.

like image 65
Nick Craver Avatar answered Sep 27 '22 16:09

Nick Craver