Skip to content

Instantly share code, notes, and snippets.

@max-mapper
Last active December 14, 2015 14:49
Show Gist options
  • Save max-mapper/5103740 to your computer and use it in GitHub Desktop.
Save max-mapper/5103740 to your computer and use it in GitHub Desktop.
brainstorming static asset APIs
// note: none of this is implemented yet -- this is just a brainstorm
// problem: there isn't a well defined solution for publishing modules to NPM that
// include their own markup and styles. consider this contrived example:
module.exports = function makesButtonBlue(buttonId) {
var button = document.getElementById(buttonId)
button.className = 'blue'
}
// this assumes the person using this module has:
// - button markup on their page already
// - a css class definition for '.blue'
// solution brainstorming follows:
// html5 template is just a string containing an
// empty set of doctype, html, head and body tags
var html = require('html5-template')
// 'html-components' will probably be implemented using cheerio
// as well as https://gist.github.com/substack/5095568
// and will work in browser + node
// the goal is to provide convenience methods for common
// stuff like inserting script tags and stylesheets
var page = require('html-components')(html)
// load pieces of a page
page.addStylesheet('./style.css')
page.body('./button.html') // sets <body> contents
// you can also drop down to the cheerio API level
page('#foo').text = 'bar'
// 'render' the page
httpServerResponse.end(page.html())
// so, to re-think the initial contrived example in a more modular way:
module.exports = function addsBlueButton(pageHTML, containerID) {
var page = require('html-components')(pageHTML)
page.addStylesheet('./style.css')
var container = page('#' + containerID)
container.html(fs.readFileSync('./button.html'))
return page
}
// benefits to this approach:
//
// - you can pass a page instance between modules and it can get
// assets dynamically added into itself
// - it would work in browser and in node
// - since the browser level asset loading APIs are being abstracted it
// means that multiple 'deployment' environments would be supported, such as
// offline apps that put assets into indexeddb, static site generators,
// server side rendered web apps and client side rendered web apps
//
// downsides:
//
// - too much abstraction?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment