Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RequireJS - Working with 2 jQuery libs

In a project I am maintaining, I am forced to stick with 2 jQuery lib calls in one page (for now at least):

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> /* 1st jQuery call */
<script>
    /* Section A - Some code that uses jQuery */
</script>

<script data-main="main" src="require.min.js">
     /* 2nd jQuery call made inside */
</script>

<script>
    /* Section B - Some code that uses jQuery */
</script>

This has been causing some weirdness in Section B that I've verified the source of the issue being the repeated inclusion of the jQuery lib.

Suppose I only have control over the AMD section - what's the best/recommended option(s) I've got to handle this situation? Thanks!

like image 756
gsklee Avatar asked Jun 01 '26 14:06

gsklee


1 Answers

jQuery is an AMD module. Not only that, it's a named AMD module, which makes it super difficult to use 2 versions of jQuery on the same page. (see this http://dvdotsenko.blogspot.com/2011/12/amd-modules-with-named-defines-so-much.html)

However, in your case you don't need 2 different versions of jQuery. You just need to use jQuery once outside of AMD and then inside of AMD code tree.

Your solution is very simple: load require.js BEFORE you load jQuery. (Translation: put the script tag that loads RequireJS before the script tag that loads jQuery.

<script src="require.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
    /* Section A - Some code that uses gloabl jQuery */
</script>
<script>
    // start the AMD code tree
    require(['main'],function(main){
        // run code that main module returns.
        // Don't know what that may mean in your case.
        // example:
        main()
    })
</script>

What happens there:

  1. requirejs loads and sets up global require and define objects
  2. jQuery loads and it (a) always sets global window.jQuery (+ window.$) and (b) if define exists and it's of AMD variety, it defines itself as named module with specific name - "jquery" <- exactly that.
  3. Your code depending on global jQuery runs.
  4. Your code depending on AMD-registered jQuery runs.

3 and 4 use one and the same exact instance of jQuery.

You absolutely must require jQuery as "jquery" No other string will give you a jQuery instance.

The only way you can alias jQuery is by creating a separate named define that repackages already-defined 'jquery' module:

define(
  'my_jquery_yey'
  , ['jquery']
  , function($){return $}
)
like image 137
ddotsenko Avatar answered Jun 04 '26 04:06

ddotsenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!