最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why is RequireJS not loading more than once a module I require multiple times? - Stack Overflow

programmeradmin12浏览0评论

When there are two file import same module, it seems to share the same resource, like this:

main.js:

require(['cmdA', 'cmdB'], function(cmdA, cmdB){

})

cmdA.js:

define(function(require, exports){
    console.log('require: cmdA');
    var body = require('body');
});

cmdB.js:

define(function(require, exports){
    console.log('require: cmdB');
    var body = require('body');
});

result:

require body 
require: cmdA 
require: cmdB 

So why not :

require body
require: cmdA
require body
require: cmdB

I think body.js is required twice,so console outputs body twice. Why?

When there are two file import same module, it seems to share the same resource, like this:

main.js:

require(['cmdA', 'cmdB'], function(cmdA, cmdB){

})

cmdA.js:

define(function(require, exports){
    console.log('require: cmdA');
    var body = require('body');
});

cmdB.js:

define(function(require, exports){
    console.log('require: cmdB');
    var body = require('body');
});

result:

require body 
require: cmdA 
require: cmdB 

So why not :

require body
require: cmdA
require body
require: cmdB

I think body.js is required twice,so console outputs body twice. Why?

Share Improve this question edited Jan 14, 2017 at 20:33 Louis 152k28 gold badges286 silver badges329 bronze badges asked Mar 14, 2014 at 16:38 gumpggumpg 951 silver badge6 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 9

By default RequireJS treats modules as singletons. Once RequireJS does it's name resolution and finds that you want module X then if you require it once, twice, three million times, you'll always get the same module object. The first time the module is required, it is created, and then the next time it is required again, you get the same module as what was returned the first time. The callback you give to define is called once, and only once.

If you use requirejs.undef, you could trick RequireJS into giving you multiple copies of a module but this is not the basic usage.

发布评论

评论列表(0)

  1. 暂无评论