My favourite #javascript 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 = Array.prototype.slice.call(arguments);
Array.prototype.forEach.call(elements, function (element) {
var innerArgs = args.slice();
innerArgs.unshift(element);
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)