简体   繁体   English

如何使用RequireJS加载页面特定的JS文件?

[英]How to load page specific JS files with RequireJS?

I have a multiple page website using RequireJS, which loads a boot strap file (boot.js), which then requires app.js. 我有一个使用RequireJS的多页网站,它加载一个引导文件(boot.js),然后需要app.js.

app.js handles all the logic, and all other module initialization happens through app.initModule() (which is just a require() call wrapper) app.js处理所有逻辑,所有其他模块初始化通过app.initModule()(只是一个require()调用包装器)发生

I also have a app.loadPageJS() to load page specific JS files (based on window.location.pathname, for example, www.domain.com/path/to/file.html would auto-load /_assets/js/pages/path/to/file.js) 我还有一个app.loadPageJS()来加载页面特定的JS文件(基于window.location.pathname,例如,www.domain.com/path/to/file.html会自动加载/ _assets / js / pages /path/to/file.js)

This feature can be turned on/off, and overridden by adding a class of "no-auto-load" or "auto-load" to the body, respectively. 可以打开/关闭此功能,并通过分别向主体添加“无自动加载”或“自动加载”类来覆盖此功能。

Now, my approach isn't robust enough. 现在,我的方法不够健全。 For one, url rewriting would break the mechanism, and for two, if loadPageJS is turned off, unless I have access to the body tag, I can't include a page specific JS file (in the case of sites using templating systems, adding a class to the body tag isn't always an option). 首先,url重写会破坏机制,对于两个,如果关闭loadPageJS,除非我有权访问body标签,否则我不能包含特定于页面的JS文件(对于使用模板系统的网站,添加body标签的类并不总是一个选项。

What are other ways to include page specific code? 包含页面特定代码的其他方法有哪些? I'd rather avoid the following: 我宁愿避免以下情况:

  • adding page specific code to a global.js file and doing if checks and only running certain code sets 将特定于页面的代码添加到global.js文件中,并执行检查并仅运行某些代码集

  • using a pageName variable (which would essentially be similar to the above) 使用pageName变量(基本上与上面类似)

Thanks in advance. 提前致谢。

If you have different modules on the page sectioned by unique ID's (a newsletter module wrapped within a div with an ID of 'newsletter', etc), you could test for existence of the module element in the DOM and conditionally load in the JS file necessary to run that module. 如果您在页面上有不同的模块,这些模块由唯一ID(包含在ID为'newsletter'的div中的新闻稿模块等)组成,您可以测试DOM中模块元素的存在并有条件地加载JS文件运行该模块所必需的。 So rather than being page-specific, it is module specific. 因此,它不是特定于页面的,而是特定于模块的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM