Skip to content

Instantly share code, notes, and snippets.

@etianen
Created September 2, 2014 09:56
Show Gist options
  • Save etianen/b9e4127dba33bbf9cdea to your computer and use it in GitHub Desktop.
Save etianen/b9e4127dba33bbf9cdea to your computer and use it in GitHub Desktop.
RequireJS setup for multi-page sites, using a single monolithic JS file.
/**
* Runs a per-page init function.
*
* The init function is chosen via the `page` config setting.
*
* This has to be defined in a separate module, since RequireJS
* does not allow passing config to the main module.
*/
define(["module"], function(module) {
var config = module.config();
// The setup routines for the different pages in the site.
var bootstrap = {
page1: function() {
// Initialize page 1.
},
page2: function() {
// Initialize page 2.
}
};
// Runs the bootstrap function for the specific page
// required by the RequireJS config.
var main = function() {
var pageBootstrap = bootstrap[config.page];
if (!pageBootstrap) {
throw new Error("Unrecognised page: ") + config.page;
}
pageBootstrap();
};
return main;
});
<!DOCTYPE html>
<html>
{% load require %}
<head>
{% require_module 'main' %}
<script>
require.config({
config: {
bootstrap: {
page: "page1"
}
}
});
</script>
</head>
<body>
</body>
</html>
/**
* Initializes the RequireJS app.
*/
require(["bootstrap"], function(bootstrap) {
// Run the bootstrap module.
bootstrap();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment