Search code examples
javascriptjqueryconflict

Avoiding jQuery conflicts in a dynamically loaded JavaScript application


I am currently trying to develop a JavaScript application that can be embedded in an existing webpage (which I cannot modify). The application needs a specific version of jQuery.

The script used for loading the application is doing the following:

// loading JavaScript needed by my application
(function () {
    document.write('<script src="../jquery-1.10.2.min.js"></script>');
    document.write(...); // load other scripts (using jQuery 1.10.2)

    // storing the application's jQuery in a new namespace 
    // to avoid conflicts with other jQuery versions
    document.write('<script type="text/javascript">' + 
        'appJQ = jQuery.noConflict(true);</script>'); // error: jQuery is undefined in IE<10
})();

// initializing the application itself
document.onload = function() {
    // ...
};

This works fine in every browser I've tested, except IE < 10. In IE 9 and lower I am getting the error that jQuery is undefined.

Moving jQuery to a new namespace in the document.onload function would work for my application but causes conflicts with other scripts on the webpage that includes my application if they need a different version of jQuery.

Do you have any suggestions how to solve this problem? Thanks for your help!


Solution

  • Instead of using document.write, try creating a <script> element and defining an onload handler for that element:

    (function () {
        var script = document.createElement('script');
        script.src = '//cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js';
        script.onload = function() {
            var appJQ = jQuery.noConflict(true);
            // app initialization code
        };
      var head = document.head || document.getElementsByTagName('head')[0];
      head.appendChild(script);
    })();
    

    If you have multiple scripts that depend on one another, you might want to try using a script loader such as HeadJS or LABjs.

    If you want even greater flexibility in managing dependencies, you can try using a module loader such as RequireJS, Browserify, or webpack.