在RequireJS示例中,它显示您可以从脚本标记中引用app.js(或任何您想调用启动文件的文件),如下所示:
<script data-main="js/app.js" src="js/require.js"></script>
由于我无法控制的原因,我不能这样做。模板层中生成的几个动态变量需要保留。因此,我创建了一个其他模块可以读取的内联"配置"模块。
<script type="text/javascript">
define('config', function() {
return {
markup_id: {
"content": "search",
"page": "index",
"media": "mobile"
},
page_context: {
"siteconfig": {
"mobile_video_player_id": /* */,
"mobile_video_player_key": /* */,
"mobile_ad_site": /* */,
"omniture_mobile_env": /* */,
"searchserver": /* */,
},
"omniture": {
"gn": /* */,
}
}
}
});
</script>
我所做的是,对于每个模板,我都放置了一个内联require.config。例如(删除了特定的路径信息):
<script type="text/javascript">
/* This code is on a template page inside a script tag. */
require.config({
baseUrl: /* */,
paths: {
'jquery': /* */,
'jquery-mobilead': /* */,
'jquery-photogalleryswipe': /* */
},
/* Enforce ordering of jQuery plugins - which require jquery */
shim: {
'jquery-mobilead': {
deps: ['jquery'],
exports: 'jQuery.fn.mobileAd'
},
'jquery-photogalleryswipe': {
deps: ['jquery'],
exports: 'jQuery.fn.photoGallerySwipe'
},
'gallery': {
deps: ['jquery-photogalleryswipe', 'jquery-mobilead']
}
},
urlArgs: 'buildlife=@buildlife@'
});
require( ['jquery', 'site', 'gallery', 'jquery-photogalleryswipe', 'jquery-mobilead'], function($, site, gallery) {
//This function will be called when all the dependencies
//listed above are loaded. Note that this function could
//be called before the page is loaded.
//This callback is optional.
/* Initialize code */
$(document).ready(function() {
/* sitewide code - call the constructor to initialize */
site.init();
/* homepage contains a reference to a function - execute the function */
gallery.initGallery();
});
}
);
</script>
我认为优化器没有办法优化模板中的代码。
但是我有符合RequireJS API文档的模块JS文件
/模块/gallery.js/模块/channel.js/模块/site.js/*等等*/
这些模块确实依赖于其他模块,但这些模块依赖于与模板内联定义的"config"模块。如果我对这些文件运行优化器,优化器是否能正常工作,因为中的一个模块config就是模板?
我想我通过阅读解决了自己的问题如何在使用AMD(require.js)的同时在Backbone.js中加载自举模型
我已经将模板变量重新构造为require全局对象,并在require.js之前声明了它。现在,模板仍然可以生成这些值,但由于require.config和require代码可以放入外部js文件中,优化器现在应该能够看到这些文件。我还没有尝试运行优化器。
<script>
/* This script block is in the template */
var require = {
config: {
markup_id: {
"content": "search",
"page": "index",
"media": "mobile"
},
page_context: {
"siteconfig": {
"mobile_video_player_id": /* */,
"mobile_video_player_key": /* */,
"mobile_ad_site": /* */,
"omniture_mobile_env": /* */,
"searchserver": /* */,
},
"omniture": {
"gn": /* */,
}
}
};
</script>
<script data-main="/m/j/main-search" src="/m/j/require.js"></script>