views:

865

answers:

3

I'm writing a snippet of code to be put on any third party website and have NO idea what environment it will be dropped into. My end goal is for the badge to be

<script src="http://example.com/js/badge.js"&gt;&lt;/script&gt;

I would like to use jQuery in my badge code to make my life easier, but I don't want to require another include on the client side (getting anything updated on the client is a pain).

This is the best I could come up with. I don't want anything before or after my script to be affected with any leftover variables or weird collisions. Does anyone see any issues?

(function() {
    function main($) {
        // do stuff with $
        $(document.body).css("background", "black")
    }

    // If jQuery exists, save it
    var old_jQuery = null;
    if (typeof(jQuery) != "undefined") {
        if (typeof(jQuery.noConflict) == "function") {
            old_jQuery = jQuery.noConflict(true);
        }
    }

    var addLibs = function() {
        // Body isn't loaded yet
        if (typeof(document.body) == "undefined" || document.body === null) {
            setTimeout(addLibs, 100);
            return;
        }

        var node = document.createElement("script");
        node.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js";
        document.body.appendChild(node);
        checkLibs();
    }

    var checkLibs = function() {
        // Library isn't done loading
        if (typeof(jQuery) == "undefined" || jQuery("*") === null) {
            setTimeout(checkLibs, 100);
            return;
        }
        var new_jQuery = jQuery.noConflict(true);
        jQuery = old_jQuery;
        main(new_jQuery);
    }

    addLibs();
})();
+2  A: 

Including jQuery again will override the $ variable, which might be an older version of jQuery or another framework. You should probably save that too.

Kobi
I thought jQuery.noConflict(True) restored $ as well. Hmm, it looks like it even reverts jQuery so I probably don't have to save that. http://docs.jquery.com/Core/jQuery.noConflict
Paul Tarjan
I stand corrected.
Kobi
How do you test it, btw? I tried setting var $=1; var jQuery=2; but I get the jQuery functions for both after your code is executed.
Kobi
+1  A: 

This works:

(function(){
    if (window.jQuery !== undefined) {
        doStuff(jQuery);
    } else {
        var script = document.createElement('script');
        script.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js';
        document.getElementsByTagName('head')[0].appendChild(script);
        var interval = setInterval(function(){
            if (window.jQuery) {
                clearInterval(interval);
                var JQ = jQuery.noConflict(true);
                doStuff(JQ);
            }
        }, 100);
    }
})();

function doStuff($) { /* Do stuff with $ */ }
J-P
Head might not be present. The original jQuery might be a funky old version with lots of plugins. The other page might have doStuff already defined.
Paul Tarjan
+2  A: 

I ended up going with http://yourock.paulisageek.com/js/popup.js . See the test (with console logging avialable) http://paulisageek.com/tmp/jquery-programatically.html. It doesn't reset jQuery and $ until jQuery actually finishes loading. Any way to block javascript without an infinite loop (which blocks the jQuery loading itself)?

// A namespace for all the internal code
var yourock = {};

// Include JQuery programatically
(function() {
    // Don't let the script run forever
    var attempts = 30;

    // If jQuery exists, save it and delete it to know when mine is loaded
    var old_jQuery;
    if (typeof(jQuery) != "undefined") {
        if (typeof(jQuery.noConflict) == "function") {
            old_jQuery = jQuery;
            delete jQuery;
        }
    }

    var addLibs = function() {
        var head = document.getElementsByTagName("head");
        if (head.length == 0) {
            if (attempts-- > 0) setTimeout(addLibs, 100);
            return;
        }

        var node = document.createElement("script");
        node.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js";
        head[0].appendChild(node);
        checkLibs();
    }

    var checkLibs = function() {
        // Library isn't done loading
        if (typeof(jQuery) == "undefined" || typeof(jQuery) != "function" || jQuery("*") === null) {
            if (attempts-- > 0) setTimeout(checkLibs, 100);
            return;
        }
        yourock.jQuery = jQuery.noConflict(true);
        if (typeof old_jQuery == "undefined")
            jQuery = old_jQuery;
    }

    addLibs();
})();
Paul Tarjan
What happened to "head might not be present" (As is the case in the test page you link to)?
itsadok
I looked up the spec and indeed the head element is guaranteed in all A-grade browsers.
Paul Tarjan