Last Updated: February 25, 2016
·
888
· steefh

lazy.js

lazy.js is a library that lets you easily create lazily initialized objects in JavaScript, meaning that an object will be initialized at the moment of its first use.

I created this small library because one of our clients had some performance issues in a JavaScript-heavy web application we built for them a short while ago. Simplified, this app is an editor for lists of lists. For each leaf item, each sublist, and the top level list on the page, a separate JavaScript controller object is created, resulting in a tree structure of controllers similar to this:

ListController
  |
  +- SubListController
  |    |
  |    +- ItemController
  |    |
  |    +- ItemController
  |    |
  |   ...
  |
  +- SubListController
  |    |
  |    +- ItemController
  |    |
  |   ...
  |
 ...

Actually, the controller tree of the app in question has more than three levels, but I think you get the idea. Now, on page load, the whole controller tree gets initialized, from the root ListController, down each SubListController branch to each ItemController leaf. Profiling the app's JavaScript showed that the ItemController objects were pretty CPU-heavy in their initialization. Specifically, the initialization contains code to provide for editing of the leaf items, and that turned out to be the main performance bottleneck when a page with a big list of lists was loaded.

Making a big structural change in the app wasn't feasible within a limited time frame, and apart from this bottleneck, the app performed nicely. Since the item edit features aren't needed -- or even shown -- directly after page load, but instead become active after user input, I guessed that lazy initialization of these edit features might give a performance boost (and it did so, substantially). That is why I created this library.

Within JavaScript, it is fairly easy to manipulate objects, and that's what this library does. It replaces methods on an object with wrapper methods that call the object's initialization method before executing the method it replaces.

Using the library is easy, all it takes to make an object lazily initialized is passing the object to a single function:

obj = Lazy.lazy('initMethodName', obj);

More information on how to use lazy.js can be found at the GitHub page for this library.