O'Reilly logo

Beautiful JavaScript by Anton Kovalyov

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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);
    }
  }
};

$(document ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required