Skip to content

Instantly share code, notes, and snippets.

@fatihacet
Created August 19, 2012 05:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save fatihacet/3392232 to your computer and use it in GitHub Desktop.
Save fatihacet/3392232 to your computer and use it in GitHub Desktop.
JavaScript module loading for seperate pages.
window.addEventListener("load", function(){
new ModuleLoader();
}, false);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>JavaScript module loading for seperate pages.</title>
<script type="text/javascript" src="ModuleLoader.js"></script>
<script type="text/javascript" src="Module1.js"></script>
<script type="text/javascript" src="Module2.js"></script>
<script type="text/javascript" src="Module3.js"></script>
<script type="text/javascript" src="main.js"></script>
</head>
<body data-module="gallery"></body>
</html>
var Module1 = function() {
this.message = 'Hello World from Module1';
this.init();
};
Module1.prototype.init = function() {
console.log(this.message);
};
var Module2 = function() {
this.message = 'Hello World from Module2';
this.init();
};
Module2.prototype.init = function() {
console.log(this.message);
};
var Module3 = function() {
this.message = 'Hello World from Module3';
this.init();
};
Module3.prototype.init = function() {
console.log(this.message);
};
/**
* Module Loader class that will instatiate corresponding class when an instance taken.
*
* @constructor
* @param {string=} moduleName Name of the module that will be instantiated.
* Default is body's data-module attribute value. If you want to take an instance of specified module,
* should pass moduleName attribute.
*/
var ModuleLoader = function(moduleName) {
this.module = moduleName || this.get();
this.create();
this.load(this.module);
};
/**
* Returns module name that is retrieved from body's data-module attribute.
* @return {string} Name of the module.
*/
ModuleLoader.prototype.get = function() {
return document.body.getAttribute('data-module');
};
/**
* Creates Modules object if one is not exist.
*/
ModuleLoader.prototype.create = function() {
if (!ModuleLoader.Modules) {
ModuleLoader.Modules = {
'home' : Module1,
'gallery': Module2,
'product': Module3
};
}
};
/**
* Be sure passed module name is exist in our Modules object,
* then instantiate that module.
*
* @param {!string} module Name of the module that will be instantiated.
*/
ModuleLoader.prototype.load = function(module) {
var modules = ModuleLoader.Modules;
module && modules[module] && new modules[module]();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment