Skip to content

Instantly share code, notes, and snippets.

@ufologist
Created June 20, 2013 07:51
Show Gist options
  • Save ufologist/5820955 to your computer and use it in GitHub Desktop.
Save ufologist/5820955 to your computer and use it in GitHub Desktop.
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
Copy link
Author

执行结果

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

@ufologist
Copy link
Author

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
Copy link

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

@tedyhy
Copy link

tedyhy commented Nov 22, 2013

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

@kwang-aa
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment