{"id":1014,"date":"2022-08-30T15:10:57","date_gmt":"2022-08-30T15:10:57","guid":{"rendered":"https:\/\/unknownerror.org\/index.php\/2013\/11\/09\/programatically-include-jquery-in-high-conflict-environment-collection-of-common-programming-errors\/"},"modified":"2022-08-30T15:10:57","modified_gmt":"2022-08-30T15:10:57","slug":"programatically-include-jquery-in-high-conflict-environment-collection-of-common-programming-errors","status":"publish","type":"post","link":"https:\/\/unknownerror.org\/index.php\/2022\/08\/30\/programatically-include-jquery-in-high-conflict-environment-collection-of-common-programming-errors\/","title":{"rendered":"Programatically include JQuery in high conflict environment &#8211;Collection of common programming errors"},"content":{"rendered":"<p>I&#8217;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<\/p>\n<pre><code>\n<\/code><\/pre>\n<p>I would like to use jQuery in my badge code to make my life easier, but I don&#8217;t want to require another include on the client side (getting anything updated on the client is a pain).<\/p>\n<p>This is the best I could come up with. I don&#8217;t want anything before or after my script to be affected with any leftover variables or weird collisions. Does anyone see any issues?<\/p>\n<pre><code>(function() {\n    function main($) {\n        \/\/ do stuff with $\n        $(document.body).css(\"background\", \"black\")\n    }\n\n    \/\/ If jQuery exists, save it\n    var old_jQuery = null;\n    if (typeof(jQuery) != \"undefined\") {\n        if (typeof(jQuery.noConflict) == \"function\") {\n            old_jQuery = jQuery.noConflict(true);\n        }\n    }\n\n    var addLibs = function() {\n        \/\/ Body isn't loaded yet\n        if (typeof(document.body) == \"undefined\" || document.body === null) {\n            setTimeout(addLibs, 100);\n            return;\n        }\n\n        var node = document.createElement(\"script\");\n        node.src = \"http:\/\/ajax.googleapis.com\/ajax\/libs\/jquery\/1.3.2\/jquery.min.js\";\n        document.body.appendChild(node);\n        checkLibs();\n    }\n\n    var checkLibs = function() {\n        \/\/ Library isn't done loading\n        if (typeof(jQuery) == \"undefined\" || jQuery(\"*\") === null) {\n            setTimeout(checkLibs, 100);\n            return;\n        }\n        var new_jQuery = jQuery.noConflict(true);\n        jQuery = old_jQuery;\n        main(new_jQuery);\n    }\n\n    addLibs();\n})();\n<\/code><\/pre>\n<ol>\n<li>\n<p>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&#8217;t reset jQuery and $ until jQuery actually finishes loading. Any way to block javascript without an infinite loop (which blocks the jQuery loading itself)?<\/p>\n<pre><code>\/\/ A namespace for all the internal code\nvar yourock = {};\n\n\/\/ Include JQuery programatically\n(function() {\n    \/\/ Don't let the script run forever\n    var attempts = 30;\n\n    \/\/ If jQuery exists, save it and delete it to know when mine is loaded\n    var old_jQuery;\n    if (typeof(jQuery) != \"undefined\") {\n        if (typeof(jQuery.noConflict) == \"function\") {\n            old_jQuery = jQuery;\n            delete jQuery;\n        }\n    }\n\n    var addLibs = function() {\n        var head = document.getElementsByTagName(\"head\");\n        if (head.length == 0) {\n            if (attempts-- &gt; 0) setTimeout(addLibs, 100);\n            return;\n        }\n\n        var node = document.createElement(\"script\");\n        node.src = \"http:\/\/ajax.googleapis.com\/ajax\/libs\/jquery\/1.3.2\/jquery.min.js\";\n        head[0].appendChild(node);\n        checkLibs();\n    }\n\n    var checkLibs = function() {\n        \/\/ Library isn't done loading\n        if (typeof(jQuery) == \"undefined\" || typeof(jQuery) != \"function\" || jQuery(\"*\") === null) {\n            if (attempts-- &gt; 0) setTimeout(checkLibs, 100);\n            return;\n        }\n        yourock.jQuery = jQuery.noConflict(true);\n        if (typeof old_jQuery == \"undefined\")\n            jQuery = old_jQuery;\n    }\n\n    addLibs();\n})();\n<\/code><\/pre>\n<\/li>\n<li>\n<p>Including jQuery again will override the <code>$<\/code> variable, which might be an older version of jQuery or another framework. You should probably save that too.<\/p>\n<\/li>\n<li>\n<p>This works:<\/p>\n<pre><code>(function(){\n    if (window.jQuery !== undefined) {\n        doStuff(jQuery);\n    } else {\n        var script = document.createElement('script');\n        script.src = 'http:\/\/ajax.googleapis.com\/ajax\/libs\/jquery\/1.3.2\/jquery.min.js';\n        document.getElementsByTagName('head')[0].appendChild(script);\n        var interval = setInterval(function(){\n            if (window.jQuery) {\n                clearInterval(interval);\n                var JQ = jQuery.noConflict(true);\n                doStuff(JQ);\n            }\n        }, 100);\n    }\n})();\n\nfunction doStuff($) { \/* Do stuff with $ *\/ }\n<\/code><\/pre>\n<\/li>\n<li>\n<p>I don&#8217;t have tested so much this code but it should work&#8230;<\/p>\n<pre><code>(function($, window) {\n    var version = ($ &amp;&amp; typeof($) == 'function' &amp;&amp; $().jquery ? ($().jquery).split('.').join('') : 0), \/\/ 1.8.1 -&gt; 181\n        jBack   = null;\n    if (version) console.log('jQuery current version : ', version);\n    else         console.log('no jQuery');\n    var loaded = function() {\n            console.log('loaded()');\n            var $ = jQuery.noConflict(true); \/\/ LOCAL own jQuery version\n            if (jBack)  {\n                window.$      = jBack; \/\/ Reassign ex-jQuery\n                window.jQuery = jBack;\n            }\n            \/\/ OK : now work with OUR new $\n            console.log('jQuery new version : ', $().jquery);\n        },\n        loadJs = function(jsPath) {\n            console.log('loadJs()');\n            var s = document.createElement('script');\n            s.setAttribute('type', 'text\/javascript');\n            s.setAttribute('src', jsPath);\n            s.onload = loaded;\n            document.getElementsByTagName('body')[0].appendChild(s);\n        };\n\n    if (version) jBack = $;\n    if (version &lt; 180) loadJs('http:\/\/code.jquery.com\/jquery-1.9.1.min.js');\n    else loaded();\n\n})((typeof(jQuery) == 'function' ? jQuery : null), window);\n<\/code><\/pre>\n<\/li>\n<\/ol>\n<p id=\"rop\"><small>Originally posted 2013-11-09 23:13:57. <\/small><\/p>","protected":false},"excerpt":{"rendered":"<p>I&#8217;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 I would like to use jQuery in my badge code to make my life easier, but I don&#8217;t want to require [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-1014","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/1014","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/comments?post=1014"}],"version-history":[{"count":0,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/1014\/revisions"}],"wp:attachment":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/media?parent=1014"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/categories?post=1014"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/tags?post=1014"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}