Javascripting by container
10-10-2010I've been working with a largeish client on a rebuild of their website.
As the content has grown, so has the Javascript code-base needed to supply the required client-side functionality. Faced with a complex set of components and logic, we've found it necessary to incorporate patterns and best practices into our development process.
One such practice is 'scripting by container'. Whenever some Javascript functionality is required, we begin by identifying the markup structure that it will be acting on.
Some examples:
- The list of podcasts on the sidebar of each article
- The navigation menu at the top of each page
- The video player on some pages
In nearly every case, we can either identify or create an container element, which will semantically define what that piece of functionality does, and which we can also use a hook for attaching event handlers.
Every piece of Javascript targets a particular markup structure, starting with its container and moving down from there into its various children.
Contexts
The Douglas Crockfords of the industry recommend that all code be enclosed by a closure of some kind - be it a named function, anonymous function, or variable assignment.
I certainly agree, but in our case, we took thing a step further:
We've defined our own context() method, which does the dirty work of finding the container for us and assigning it to 'this'. Now we have a simple, re-usable function that we can apply across our code base and enforce as a coding standard.
By limiting it to one context() call per Javascript file, and naming our Javascript files the same as our containers, we ensure a highly readable code-base.
Advantages:
- We can see at a glance what each Javascript module does and which markup structures it affect.
- Less merging required between 6 developers
- Better performance. The code for each container only runs if that container exists on the page.