An example component of this might be responsive images. By default our users get served a small image which means mobile devices get a small initial payload, and everyone gets at least an image. We can then enhance this image by picking a more appropriate size from our image resizing service in a progressive manner for users with more capable machines. Given how big a proportion of our content images are this gives us significant savings without unnecessarily losing quality on larger screens.
A typical JS module has three key methods:
- The constructor, which takes a reference to the DOM node to enhance (also maybe some config)
- An 'init' method which triggers the enhancement (it could do so lazily, so the better resolution image isn't loaded in until the user starts scrolling down)
- A 'destroy' method which removes any event listeners, etc
This structure makes unit testing straight forward (there is some debate about whether the constructor should also init, but I don't like constructors with side effects on the DOM...), and also a fairly straight forward way of using these modules in different contexts.
The document then being delivered then has a controller (for lack of a better word), which performs selections (using querySelector) and the initiates the various modules. We use Require.JS as a module mechanism to encapsulate these classes which works well for us.