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() {
return jQuery;
});
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:
define(['jquery'], function($) {
// module code using "$" goes here
});