Load jQuery before RequireJS and still use it as dependency

If you use RequireJS and jQuery in a project, you might find yourself
in a situation, where you embed jQuery before RequireJS, but still need to have
the “jquery” dependency respected. Unfortunately, in the usual scenario it’s
essential, that RequireJS is loaded before jQuery to provide the
define() method, that jQuery registers it with.

<!-- this will fail with an error: --><script src="jquery.js"></script><script src="require.js"data-main="main.js"></script><!-- likewise, if you optimized the main.js file but excluded jQuery -->

So, if you have already loaded jQuery but need to refer to it in other
modules, e. g., like define(["jquery"], ...), you find yourself in
the nasty situation, that the browser tells you, that this module “jquery”
couldn’t be found.

We have therefore to manually repeat the steps the jQuery library itself
does to register as module. Put this at the top of your main.js file:

define('jquery',[],function(){returnjQuery;});

and you’re set. These lines mimic the according
part in jQuery, which isn’t executed due to the lack of
define(), when it was reached. Now you can happily define modules
depending on “jquery” and even optimize it with r.js excluding the jQuery file
itself:

Welcome! This is the personal website of Manuel Strehl. I’m a Germany based web developer and frontend engineer with a strong attitude towards web standards. If you like this site, you can subscribe to the newsfeed or follow me on Twitter.

I’d like to point out, that I use Piwik to analyse what’s going on on this site. If you don’t like being tracked, you can here opt-out at any time. For other privacy-related issues please see the imprint.