18

I'm writing a script that's meant to be embedded on 3rd party sites to add functionality to them. I recently ripped out my rather messy custom loader code and started replacing it with requirejs. One of the libraries that optionally gets loaded for me (depends on some parameters passed in) is jQuery.

This works well, until my script is included on a page that jQuery is already on, in which case, what appears to happen is some plugins partway load, requirejs loads jQuery over the page's version, and the plugins promptly break.

Asking clients to rewrite their pages just to use this script is out of the question, so what I would like to do is detect if jQuery is already loaded, if it is, skip loading it through requirejs, and just use the already loaded one (This will possibly open me up to odd edge cases and bugs when they're using a much older version of jQuery, but I don't have much choice).

What I thought I would do is write a new module, that would first see if jQuery is loaded, if it is, just export the jQuery object, if it's not, then load it, then do the export. However, I appear to be stymied, as the definition function for the module appears to need to be synchronous to work, so I can't go off and load another script, which would be asynchronous, then stuff the export into requirejs.

Am I missing something in the docs? Is what I'm attempting impossible?

Matt Sieker
  • 9,349
  • 2
  • 25
  • 43
  • Would it help to be able to [load two different versions of jQuery at the same time](http://stackoverflow.com/q/1566595/33732)? – Rob Kennedy Sep 04 '12 at 16:54
  • That would solve the versioning issues. However, this doesn't seem to solve the plugin trampling, as more than likely the on page version will load before mine, and not have noconflict on. I suppose I could modify my served version of jQuery to not trample on the $/jQuery objects, and just expose itself as a module, but I'd rather do that as a last resort, since then I would have to remember to make that change when I update jQuery. – Matt Sieker Sep 04 '12 at 16:59
  • 1
    That shouldn't matter. Only one of the libraries needs to be aware of no-conflict mode. When you call `noConflict` on your copy of jQuery, the values of `$` and `jQuery` get restored to the originals, from before your copy was loaded. Plug-ins that used the original instance will continue to refer to it. The original jQuery instance will assume it's the only one, which is fine. – Rob Kennedy Sep 04 '12 at 17:27

3 Answers3

26

I had the same issue on a similar project, using require.js for a library intended to be loaded on 3rd-party sites. You can see my approach here, but here's the simplified version:

// check for existing jQuery
var jQuery = window.jQuery,
    // check for old versions of jQuery
    oldjQuery = jQuery && !!jQuery.fn.jquery.match(/^1\.[0-4](\.|$)/),
    localJqueryPath = libPath + 'jquery/jquery-1.7.2.min',
    paths = {},
    noConflict;

// check for jQuery 
if (!jQuery || oldjQuery) {
    // load if it's not available or doesn't meet min standards
    paths.jquery = localJqueryPath;
    noConflict = !!oldjQuery;
} else {
    // register the current jQuery
    define('jquery', [], function() { return jQuery; });
}

// set up require
require.config({
    paths: paths 
});

// load stuff
require(['jquery', ... ], function($, ...) {

    // deal with jQuery versions if necessary
    if (noConflict) $.noConflict(true);

    // etc

});

As you can see, this looks for jQuery, and then either defines the "jquery" module as a wrapper for the existing library, or (if there's no jQuery or if the existing jQuery is an old version) loads the library-specific jQuery with noConflict.

This works pretty well. The only downside is that you're calling require() dynamically within your script, which makes it more difficult to use the r.js optimizer effectively.

nrabinowitz
  • 55,314
  • 10
  • 149
  • 165
  • Nice code. The oldjQuery regex does not work for jQuery >= 1.10 though. – Christof Jul 08 '13 at 08:57
  • i have a similar question here http://stackoverflow.com/questions/20291793/adding-requirejs-module-that-uses-jquery-on-a-page-that-already-has-jquery-as-a . How do you not use a `map` as suggested in the API? What would you do if you wanted to load a third version of jquery for another module? – gillyspy Nov 29 '13 at 21:19
3

I had a similar issue.. My script was reloading jQuery twice .. Used the solution from the comments in this article

Worked like a charm !!

(Comment which worked was :

"I put it on my config file after the requirejs.config(...) and before the requirej(["app"]) and it worked")

srini
  • 452
  • 4
  • 10
0

With some toying around with srini's solution, I was able to get a 'conditional' means to load jquery within requirejs only if it's not already loaded by the web page. In my main.js near the top (I'm also loading angular):

requirejs.config({
    "baseUrl": "./app/",
    "paths": {
        "jquery"            : "https://code.jquery.com/jquery-3.6.0.min.js",
        "angular"           : "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min"
    },
    "shim": {
        "jquery": {
            "exports" : "$"
        },
        "angular": {
            "exports" : 'angular'
        }
    }
})

// don't load jquery if it is already loaded
if(typeof(jQuery) == 'function') {
    // define 'jquery' so requirejs knows how to get it
    define('jquery', [], function() {
        return jQuery;
    });
} else {
    // require (preload) jquery so it's available in requirejs
    requirejs(['jquery'], function( $ ) {
        return $; // optional
    });
}

I confirmed with a local copy of jquery in which I added a 'console.log()' at the top that it was only being loaded once. I also tested with a script tag in my html file and without, referencing '$' in both a service method and a controller method and both worked with or without the script tag.

Scott
  • 7,983
  • 2
  • 26
  • 41