Question

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!

Was it helpful?

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.

OTHER TIPS

Following Hamza's answer, you can use this method of loading in a different way:

var s = document.createElement("script");
s.src = "../jquery.min.js"     // insert your own jQuery link
s.onload = function() {
    var appJS = jQuery.noConflict(true);
}

Hope this helps.

The document.write calls would also happen after the document is considered loaded, in which case your onload function might fire before the contents of that first function. You want to load the javascript files in a better way, such that their onload initiates the application itself.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top