I'm using RequireJs 2.0 (or attempting to use).
Currently, my assets are grouped into to parts, "General" and "Custom". All pages, should use the General scripts, while only some pages should use the Custom.
From what I can tell RequireJs, accepts one data-main
value which holds your config and basically your module require's. This is fine if all pages use the same assets, but how would I add an additional data-main
script for Custom pages?
Thank you!
Use your data-main
attribute to load your General script. On the custom pages, wherever you're about to do something that requires a Custom module, just wrap it in a require
call. Your master page (or template or layout or whatever it's called on your server platform) would have this:
<html><head>
<script language="javascript" src="require.js" data-main="general" ></script>
</head>
Your custom page markup can look like this (syntax from memory; double-check!)
<p class="funny">I'm a funny paragraph</p>
<script language="javascript">
require(['funny-stuff'], function(fs) {
fs.doSomthing();
});
</script>
The funny-stuff
module would only get loaded by pages that ask for it. If you don't want to or can't have separate markup on some pages, you can dynamically load a dependency from your main script by wrapping a require
call inside an if
statement. Within general.js
:
// Determine if we need the custom module
if (isFunnyPage()) {
require(['funny-stuff'], function(fs) {
fs.doSomething();
});
}
You do have to be careful when you run the optimizer, because it will find the dependency referenced in the require
call, and by default package it with your main file. So you would need to configure the optimizer to exclude the custom modules.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With