RequireJS different jQuery

2019-06-14 02:08发布

问题:

I would like to use RequireJS to load jQuery (module I develop supposed to work in uncontrolled environment where jQuery might be already initialized), but there are some problems when require different versions of jQuery. Results are unexpectable. Inside require function block jQuery version is kind of random. What is wrong? Here is code to illustrate problem:

<!DOCTYPE html>
<html>
<head>
    <script data-main="scripts/main" src="http://ajax.cdnjs.com/ajax/libs/require.js/0.24.0/require.min.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
</head>
<body>

<script>
    console.log(jQuery.fn.jquery);

    setTimeout(function(){
      require(["http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"], function() {
      console.log($.fn.jquery);
      });
    },1000);
    setTimeout(function(){
      require(["http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js"], function() {
      console.log($.fn.jquery);
      });
    },2000);

    setTimeout(function(){
      require(["http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.js"], function() {
      console.log($.fn.jquery);
      });
    },3000);

    setTimeout(function(){
      require(["http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js"], function() {
      console.log($.fn.jquery);
      });
    },4000);

    setTimeout(function(){
      require(["http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"], function() {
      console.log($.fn.jquery);
      });
    },5000);

    setTimeout(function(){
      require(["http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"], function() {
      console.log($.fn.jquery);
      });
    },6000);

    setTimeout(function(){
      require(["http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js"], function() {
      console.log($.fn.jquery);
      });
    },7000);

    setTimeout(function(){
      require(["http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.js"], function() {
      console.log($.fn.jquery);
      });
    },8000);

    setTimeout(function(){
      require(["http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"], function() {
      console.log($.fn.jquery);
      });
    },9000);
</script>
</body>
</html>

Results are:

1.6.2
1.8.0
1.4.4
1.8.0
1.8.0
1.6.2
1.6.2
1.6.2
1.6.2
1.6.2

回答1:

Assuming you are using AMD (Asynchronous Module Definition) compatible versions of jQuery, the jQuery object should be made available as the first argument of the function :


require(["some_version_of_jquery.js"], function(jQuery) {
      console.log(jQuery.fn.jquery);
      });

So the jQuery object available inside the function is defined in local scope rather than the globally defined one.

If you are not using AMD compatible versions, then you will have to use RequireJS Shim config.