The idea is to identify, from the same script tag that loads RequireJS, the appropriate main logic module to be loaded. This is done by adding a data-id
and a data-logic
attribute to the RequireJS script tag.
The data-id
attribute is used to identify the RequireJS script tag while the data-logic
is used to specify the main logic module to load. Using data-id
over id
attribute is preferred simply because of technical correctness as scripts do not have an id
attribute.
Say we have the following dir structure:
web/
js/
lib/
require.js
jquery.min.js
config.js
home.js
login.js
homepage.html
loginpage.html
If the script home.js
holds the logic for the homepage then the corresponding script tag would be:
// homepage.html
<script data-id="requirejs" data-logic="home" data-main="js/config" src="js/lib/require.js"></script>
Similarly, if login.js
holds the logic for the loginpage then the corresponding script tag would be:
// loginpage.html
<script data-id="requirejs" data-logic="login" data-main="js/config" src="js/lib/require.js"></script>
Then in js/config
, the main logic module is loaded using the value of data-logic
attribute.
// config.js
require.config({
baseUrl: 'js',
paths: {
// fallback to local in case CDN fails
jquery: ['https://code.jquery.com/jquery-2.1.1.min', 'lib/jquery.min'],
}
});
// Load app logic as specified in `data-logic` attribute
require([document.querySelector('script[data-id="requirejs"]').getAttribute("data-logic")]);
While this approach requires the use of non-standard attributes, it also lends to a terser and less cluttered way of separating the config from the main logic module.