1

I am looking at integrating RequireJS into an existing web application which does not use AMD. The page I will be including my scripts on will already include a number of scripts, including jQuery and some common in-house scripts.

I was curious what would happen if I loaded some of these scripts with Require after they had already been loaded in a traditional <script> tag. Here is what I tried:

index.html

<script src="js/lib/jquery.js"></script>
<script src="js/lib/require.js" data-main="js/init.js"></script>

init.js

require.config({
   paths: { 
      jquery: "js/lib/jquery"
});
require(["jquery"], function($) {
   //Do stuff
});

My hope was that Require would be smart enough to see that js/lib/jquery.js was already loaded on the page, and use it as a module, rather than reloading the script. I then inspected the page contents and found that Require had in fact reloaded the script:

<script type="text/javascript" src="/js/libs/jquery.js"></script>
...
<script type="text/javascript" charset="utf-8" async="" data-requirecontext="_" data-requiremodule="jquery" src="/js/libs/jquery.js"></script>

I understand that this is probably a bit of a reach to expect Require to be smart enough to do what I wish it would, but it would be really handy for devs integrating Require with an existing site if it worked this way. That way you could move legacy scripts into AMD modules at your leisure, without having to even change your require code. Maybe I'm just dreaming, though. :)

Anyone have any ideas how to do this?

brettjonesdev
  • 2,271
  • 1
  • 18
  • 23

1 Answers1

1

Strangely enough, if you swap the order of your script tags, it should work fine for jQuery:

<script src="js/lib/require.js" data-main="js/init.js"></script>
<script src="js/lib/jquery.js"></script>

jQuery has code that checks if AMD loader is present before defining a module named "jquery", so if RequireJS is not loaded first then that module won't be registered.

This will not be true of your in-house scripts unless you modify them to check for presence of AMD loader as well. See here for background on how to do this: When designing a JS library should I make it RequireJS/AMD compatible or not?

Since the data-main script is loaded async you should be able to assume that the scripts for jquery and requirejs will load first before your init.js, but to make it less confusing you might just do it like this:

<script src="js/lib/require.js"></script>
<script src="js/lib/jquery.js"></script>
<script src="js/init.js"></script>
Community
  • 1
  • 1
explunit
  • 18,967
  • 6
  • 69
  • 94
  • Ah, yes jQuery does do that `define.amd` check these days. Yes, this would be a fine way to get by for jQuery, but you're right - it won't really help me with in-house script. :/ – brettjonesdev Aug 21 '13 at 19:24