Use jQuery as a dependency without loading jQuery

2019-05-15 10:56发布

问题:

Consider the following page:

<html>
<head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
</head>
<body>
    <script data-main="app" src="require.js"></script>
</body>
</html>

How can i use jQuery as a dependency for RequireJS modules when it's not loaded with RequireJS? I know jQuery exposes itself as a global AMD module, so i should be able to add it as a dependency, but i'm not quite sure how to.

I would like to be able to do the following:

require(['jquery'], function() {
    console.log('success')
});

And if jQuery has not yet finished loading, it should wait for it to complete, and then continue. Is this possible to do?

回答1:

Load jQuery second, RequireJS first. Run your main module when both are loaded.

<html>
<head>
    <script src="require.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
</head>
<body>
    <script>
        require(["app"], function(app){
            app.runMe()
        })
    </script>
</body>
</html>

jQuery will NOT register itself as AMD module if it does not see define.amd floating around. The only way to make it register itself properly is to load RequireJS before jQuery.



回答2:

You should define jquery as a shim as following:

requirejs.config({
  shim: {
    'jquery': {
        exports: '$'
    }
  },
  path : {
    jquery : '$PATH/jquery.js'
  }
});


回答3:

One way to do this is to use the data-main attribute to load a main.js file with require.js:

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

where the main.js file is a flavour of:

requirejs.config({
    shim: {         // regard the shim structure as a dependency map
        'jquery': [],
        'app': ['jquery']    // app code will not execute before jquery is loaded
    },
    waitSeconds: 20
});

require(
    [
        'jquery',
        'app'
    ],
    function(
        $
    ) {
        //the plugins from the dependency array have been loaded.
        console.log ("jQuery and app loaded through require.js");
    }
);

The example above assumes that you load jquery.js from the same location as require.js (which is, your site)