Search code examples
jqueryajaxyuijavascript

Standard way to include javascript library from javascript


I'd like to pull in the jquery library from my javascript include.

Does this work 100% of the time? Is there a better way?

(function() {

var loadJquery = function (cb) {
    var addLibs = function () {
        if (typeof(document.body) == "undefined" || document.body === null) {
            setTimeout(addLibs, 100);
            return;
        }

        var node = document.createElement("script");
        node.src = "http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js";
        document.body.appendChild(node);
        checkLib();
    };

    var checkLib = function () {  
        if (typeof($) == "undefined" || $("*") === null) {
            setTimeout(checkLib, 100);
            return;
        }
        cb($.noConflict());
    }
    addLibs();
}

loadJquery(function($){
  // Do stuff with $
  $(document.body).css("background", "black");
});

})();

Change the node.src and $.noConflict to YUI if you want YUI3, or YAHOO if you're YUI2, etc.


Solution

  • From posting on our internal mailing lists at work, I was pointed to this:

    There are many cross-browser edge cases involved in dynamically injecting scripts. If rolling the YUI 3 seed file into your script isn't an option and if you can't depend on the property to already have the YUI 3 seed loaded, I'd recommend using LazyLoad (shameless plug) to bootstrap your script: http://github.com/rgrove/lazyload/

    You can merge lazyload.js into your script, then use something like this to load the YUI 3 seed if it's not already on the page:

    (function () {
       function init() {
         YUI().use('node', function (Y) {
           // ... do my stuff ...
         });
       }
    
       if (YUI) {
         init();
       } else {
         LazyLoad.js('http://yui.yahooapis.com/3.0.0/build/yui/yui-min.js',
    init);
       }
    })();