Can I limit the amount of jQuery version I need using noConflict () if the order of loading other scripts is unknown?

I want to enable a specific version of jQuery on a page that I don’t control (e-commerce platform) asynchronously, and use it only in my script. Other scripts can be loaded on the page, which can also do the same, and I do not know the order in which the page includes my script and others.

Using jQuery.noConflict([removeAll]), I can guarantee that:

  • my script gets the correct jQuery version
  • Am I not overwriting the jQuery version for anyone else?

I think this question is different from most other questions with multiple versions of jQuery because people make assumptions about the order in which the script is included and do not use jQuery asynchronous loading with callbacks.

Thank!

+4
source share
1 answer

Here is my attempt (can someone confirm that this is normal?):

myscript.js

(function() {

  var myJQuery;

  function loadjQuery(url, callback) {
    var runCallbackOnSuccess = function() {
      if (typeof jQuery != "undefined") {
        myJQuery = jQuery.noConflict(true);   // NOTICE THIS LINE
        callback();
      }
    };
    var scriptTag = document.createElement("script");
    scriptTag.setAttribute("src", url);
    scriptTag.onload = runCallbackOnSuccess; 
    document.getElementsByTagName("head")[0].appendChild(scriptTag);
  }

  function doSomethingInMyScript() {
    myJQuery(document).ready(....);
  }

  loadjQuery("https://code.jquery.com/jquery-A.B.C.min.js", doSomethingInMyScript);
})();

otherscript.js (out of my control, but assuming so)

(function() {
  function loadjQuery(url, callback) {
    <same as above, but without the noConflict() call>
  }

  function doSomethingInOtherScript() {
    jQuery(document).ready(....);
  }

  loadjQuery("https://code.jquery.com/jquery-X.Y.Z.min.js", doSomethingInOtherScript);
})();

Will this code work independently of it:

  • whether the first page includes myscript.js or otherscript.js
  • are callback functions performed for myscript.js or otherscript.js?

, , jQuery, script jQuery .

0

All Articles