My favourite progressive-enhancement+AMD requirejs abstraction: enhanceEach

It covers what is for me an extremely common use-case, of

“I have a bunch of elements with some class which means that I want to progressively-enhance them, only loading the code required to do so in to pages which contain the elements”

var enhanceEach = function (selector, dependencies, callback) {
    var elements = document.querySelectorAll(selector);
    if (elements.length > 0) {
        require(dependencies, function () {
            var args =;
  , function (element) {
                var innerArgs = args.slice();
                callback.apply(callback, innerArgs);

A typical example, activating CodeMirror on textareas with class|=codemirror if there are any on the page:

enhanceEach('textarea.codemirror', ['codemirror/lib/codemirror', 'codemirror/mode/htmlmixed/htmlmixed'], function (el, CodeMirror) {
    var config = {
        indentUnit: 1,
        tabSize: 2
    if (el.hasAttribute('data-codemirror-mode')) {
        config['mode'] = el.getAttribute('data-codemirror-mode');
    var codemirror = CodeMirror.fromTextArea(el, config);

(A fan of minimal, useful javascript abstractions, and the thought processes behind them? You may enjoy A Minimal Javascript HTTP Abstraction)

— 2 comments 1 reposts 1 likes