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"></script> 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? Any better solutions? The main one I see is the time between the start of the anonymous function, and the end of checkLibs is not going to block other scripts which might rely on window.jQuery being available. Can you block other scripts in javascript? // Namespace if (typeof yourock == "undefined") yourock = {}; // Api function yourock.popup = function(id) { // Library isn't done loading if (typeof(yourock.jQuery) == "undefined" || yourock.jQuery("*") === null) { setTimeout(yourock.popup, 100); return; } // Shorthand var $ = yourock.jQuery; // Do stuff } // Load libraries (function() { // If jQuery exists, save it and delete it to know when mine is loaded var old_jQuery = null; 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) { 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" || jQuery("*") === null) { setTimeout(checkLibs, 100); return; } yourock.jQuery = jQuery.noConflict(true); jQuery = old_jQuery; } addLibs(); })();