CHAPTER EIGHT

Evolution

In March 2009, Paul Irish published a blog post, “Markup-based Unobtrusive Comprehensive DOM-ready Execution,” describing a solution to a pesky problem familiar to every newcomer to the world of client-side JavaScript at the time: executing only the code that was required for a given page.

Back in 2009, it was common for client-side JavaScript developers to just put all of their code—for all of their pages—inside one giant $(document).ready() callback; some were a bit cleverer, and tested for the presence of an element with a certain ID in order to determine the page they were on. A newcomer to such code struggled mightily to mentally parse hundreds of lines where function declarations, anonymous functions, and long chains of jQuery methods intermingled.

The method proposed in this blog post was simple: put a class on the <body> element, and then use a simple helper function to look up a corresponding initialization method in an application object:

UTIL = {
  loadEvents : function () {
    var bodyId = document.body.id;

    $.each(document.body.className.split(/\s+/), function (i, className) {
      UTIL.fire(className);
      UTIL.fire(className,bodyId);
    });
  },

  fire : function (func, funcname, args) {
    var namespace = APP;  // indicate your obj literal namespace here

    funcname = (funcname === undefined) ? 'init' : funcname;

    if (
      func !== '' &&
      namespace[func] &&
      typeof namespace[func][funcname] == 'function'
    ) {
      namespace[func][funcname](args);
    }
  }
};

Get Beautiful JavaScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.