Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
RequireJS load module mechanism
require(['main'], function(main) {
main.hello();
});
<!DOCTYPE html>
<html>
<head>
<title>Hello RequireJS boilerplate</title>
<meta charset="utf-8" />
</head>
<body>
<h1>RequireJS load module mechanism</h1>
<p>Open your console</p>
<ol>
<li>require module: mod1</li>
<li>require module: mod2</li>
<li>require module: main</li>
<li>hello mod1</li>
<li>hello mod2</li>
<li>hello main</li>
</ol>
<h2>Conclusion</h2>
<p>RequireJS execute module as <strong>SOON</strong> as possible(RequireJS会先尽早地执行[依赖]模块, 相当于所有的require都被提前了, 而且模块执行的顺序也不一定100%就是先mod1再mod2)</p>
<p>So DO NOT trust your code!(因此你看到执行顺序和你预想的完全不一样! 颤抖吧~ RequireJS!)</p>
<strong>Orz!</strong>
<p>Test with RequireJS 2.1.6</p>
<script data-main="js/app.js" src="lib/require.js"></script>
</body>
</html>
define(function(require, exports, module) {
console.log('require module: main');
var mod1 = require('mod1');
mod1.hello();
var mod2 = require('mod2');
mod2.hello();
return {
hello: function() {
console.log('hello main');
}
};
});
define(function(require, exports, module) {
console.log('require module: mod1');
return {
hello: function() {
console.log("hello mod1");
}
};
});
define(function(require, exports, module) {
console.log('require module: mod2');
return {
hello: function() {
console.log("hello mod2");
}
};
});
@ufologist

This comment has been minimized.

Copy link
Owner Author

ufologist commented Jun 20, 2013

执行结果

require module: mod1
require module: mod2
require module: main
hello mod1
hello mod2
hello main

@ufologist

This comment has been minimized.

Copy link
Owner Author

ufologist commented Jun 20, 2013

RequireJS execute module as SOON as possible(RequireJS会先尽早地执行[依赖]模块, 相当于所有的require都被提前了, 而且模块执行的顺序也不一定100%就是先mod1再mod2)
So DO NOT trust your code!(因此你看到执行顺序和你预想的完全不一样! 颤抖吧~ RequireJS!)
Orz!
Test with RequireJS 2.1.6

@xionglun

This comment has been minimized.

Copy link

xionglun commented Jul 22, 2013

模块顺序不一定100%是什么意思? 是require的时候不能做到顺序一致性还是被调用执行的时候不能做到一致性?

@tedyhy

This comment has been minimized.

Copy link

tedyhy commented Nov 22, 2013

感觉require.js不靠谱呢,试试seajs吧

@kwang-aa

This comment has been minimized.

Copy link

kwang-aa commented May 25, 2015

即使加载的顺序有差异,但是执行顺序是正确的呢。
所以,无所谓吧。
执行顺序才是我们所真正关心的吧。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.