Skip to content

Instantly share code, notes, and snippets.

@jmorton
Created October 19, 2012 18:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmorton/3919665 to your computer and use it in GitHub Desktop.
Save jmorton/3919665 to your computer and use it in GitHub Desktop.
Augment yer DOM with Augmenter
/**
* Usage:
*
* <script src="augmenter.js" type="text/javascript"></script>
* <script>
* new Augmenter({ attr: 'data-employee', url: '/employee?id=' })
* </script>
*
* Any elements like this in your document:
*
* <div data-employee="1234">Me</div>
*
* ...will be updated with whatever document is returned by the construced
* URL. In my case, that is something like:
*
* <div class="vcard">
* <img class="photo" src="http://example.com/public/employees/1234/avatar.jpg">
* <span class="fn">Jonathan Morton</span>
* <div class="title">Software Engineer</div>
* <div class="org">Technology</div>
* <div class="adr">
* <span class="locality">McLean</span>
* <span class="region">Virginia</span>
* </div>
* </div>
*
*/
var Augmenter = function(cfg) {
var match = function(el) {
return el.querySelectorAll('[' + cfg.attr + ']');
};
var id = function(el) {
return el.getAttribute(cfg.attr);
};
var urlize = function(id) {
return cfg.url+id;
};
var identify = function(root) {
var el, els = match(root);
for (var i = 0; i < els.length; i++) {
el = els[i];
fetch(id(el),augment(el));
};
};
var fetch = function(id, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', urlize(id),true);
xhr.setRequestHeader('Accept','text/html');
xhr.send();
xhr.onload = callback;
};
var augment = function(element) {
return function(evt) {
var response = evt.target.response;
element.innerHTML = response;
};
};
document.addEventListener("DOMContentLoaded", function() {
console.debug("Eager loading on DOMContentLoaded.");
identify(document);
}, false);
document.addEventListener("DOMNodeInserted", function(evt) {
console.debug("Eager loading on DOMNodeInserted.");
var el = evt.target;
if ((el instanceof Element)) {
identify(el);
}
}, false);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment