Tiny, efficient DOM components

DISCLAIMER: Work in progress

Getting started

Download uncompressed (~ 6,5KB) or minified (~ 4KB)

Currently Sprig depends on jQuery.

Usage examples

Register the hello-world component by calling the Sprig.add() function. It takes two parameters, componentId and setupFunction

The setupFunction is called whenever an element with the attribute data-sprig-component='hello-word' is inserted to the DOM.

Sprig.add('hello-world', function(elopts) {
  el.innerHTML = "Hello World!";

Inserting a hello-world component to the body:

document.body.innerHTML = '<div data-sprig-component="hello-world"></div>';
Sprig.load(document.body); // <-- can be skipped in newer versions of Chrome and Firefox 

Will result in:

Hello World

Components inserting other components just works:

Sprig.add('parent', function(elopts) {
  el.innerHTML = 'I am the parent. This is my child: <div data-sprig-component="child"></div>';
Sprig.add('child', function(elopts) {
  el.innerHTML = 'I am the child.';

Inserting a parent component to the body:

document.body.innerHTML = '<div data-sprig-component="parent"></div>';

... will result in:

I am the parent. This is my child:
I am the child.

For convenience, all the HTML5 data-* attributes defined on the element are passed as second parameter to the setupFunction

For newer browsers this is a reference to the elements' dataset property

Sprig.add('hello-planet', function(elopts) {
  el.innerHTML = 'Hello '+(opts.planet || 'mysterious planet');

Inserting this hello-planet component to the body:

document.body.innerHTML = '<div data-sprig-component="hello-planet"></div>';
var moon = document.createElement("div");
moon.setAttribute("data-sprig-component", "hello-planet");
moon.setAttribute("data-planet", "moon");

... will result in:

Hello mysterious planet
Hello moon

Quite often you'll need to request data from the server, wait for the server to return it before displaying it.

If the setupFunction takes three parameters, it is assumed to be async, and will pass a done function that is to be called when the asynchronous action is complete.

Sprig.add('async-component', function(eloptsdone) {
  $.get("/some/data.json").then(function(data) {
    el.innerHTML = "The server gave me this value: <b>"+data.value+"</b>";
  el.innerHTML = "Requesting data from server...";

How does it work?

In bleeding edge browsers supporting Mutation Observers (currently only Chrome and Firefox), Sprig works by observing changes to the DOM tree. This, however, only works for nodes inserted dynamically from JavaScript. If you serve a HTML file already layed out with components, then you will have to set them up initially, e.g. on domReady, like this:

$(function() {