Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 968
Paul Tarjan Avatar asked Oct 28 '09 23:10

Paul Tarjan


1 Answers

There's only one issue I can think of with this approach (and this has come up twice in questions on SO in the last month).

The issue is that jQuery as of 1.3.2 cannot detect if the document is loaded if it is itself included after the document has loaded (i.e. dynamic <script> inclusion as you are doing, bookmarklet, etc) in non-IE browsers. In such cases the function passed to .ready() will never be called.

Here is the bug report for the issue: http://dev.jquery.com/ticket/4196 Nothing has happened with it for the last 8 months.

Now, the way you have designed loadJquery as I see it should effectively replace $(document).ready() so you may not need to worry. But any code that is written in the $(document).ready() function-passing style will not execute.

like image 200
Crescent Fresh Avatar answered Sep 21 '22 04:09

Crescent Fresh