Update-
我添加了一个使用 RequireJS 和模块化 HTML 组件的示例。包含构建工具示例 -https://github.com/simonsmith/modular-html-requirejs
我还写了一篇关于此的博客文章 -http://simonsmith.io/modular-html-components-with-requirejs/
只使用的方法main.js
因为一切都是可能更适合单页应用程序.
我处理这种情况的方法是只在main.js
file:
在每个页面上:
<script src="require.js" data-main="main"></script>
main.js
require.config({
// config options
});
require(['jquery', 'common/ajaxLoader', 'common/someOtherModule'], function($, ajax, otherModule) {
// Modules that do stuff on every page are instantiated here
});
第1页.html
<script>
require(['scripts/page1']);
</script>
page1.js
require(['jquery', 'page1Module'], function($, module){
// page1 specific stuff here
});
上面的例子只是处理它的几种方法之一。笔记加载纯 JavaScript 文件和模块之间的区别.
我遵循的经验法则是将所有可重用模块(或类,如果它更容易概念化)保留在一个define
具有自己的依赖项等,然后使用require
获取这些模块,使用它们的方法或以某种方式与它们交互。
使用此模式几乎肯定需要使用 domReady 模块这是 RequireJS 的一个单独的插件。用这个而不是 jQuery 中的现成函数例如,它允许模块在 DOM 准备好之前开始下载,从而减少代码执行的等待时间。
Edit您可能希望请参阅多页面应用程序的另一个示例在 RequireJS 存储库中