Writing efficient JavaScript modules

Writing modular JavaScript gives you many advantages:
- reusable code
- separation of layout and logic
- prevent code duplication
- cleaner and easier to read

However there are still a few common mistakes which can be made, even when following guides. I've listed some of those below.

1) Putting your JavaScript code at the bottom of the html page prevents JavaScript from blocking the  browser rendering.

<!doctype html>
<meta charset="utf-8" />
<title>Module Example</title>
<div id="example"></div>
<script src="js/modules/Module.js"></script>

2) When writing a JavaScript Class The function should only hold the unique properties of the module. Things like the html dom element and it's options. These are duplicated for each instance of the module so 1000 modules means 1000 references to elements and 1000 sets of options.

function Module(id, options) {
this.el = this.getEl(id);
this.options = options;

3) The prototype should only hold the shared properties of the module. This is important as by adding it to the prototype, the object is only ever stored once in browser memory, even if you create 1000 instances of the module!

Module.prototype = {
name: 'Module',
elements: {},
init: function() {
this.el.innerHTML = 'options: <pre>'+JSON.stringify(this.options)+'</pre>';
getEl: function(id) {
if (this.elements[id]) {
return this.elements[id];
else {
this.elements[id] = document.getElementById(id);
return this.elements[id];

4) Now you can create instances of your module which will be very efficient and quick. In this example I have also added a caching function to the elements to ensure each element is only located and referenced once!

var module = new Module('example', {
test: 'hello world',
param: 23476

No comments:

Post a Comment