choo-lazy-view
![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat-square)
Lazily load view views as they are invoked by the router. Built for split-require but sohuld work with any software with a similar callback signature.
Usage
var splitRequire = require('split-require')
var LazyView = require('choo-lazy-view')
var html = require('choo/html')
var choo = require('choo')
var app = choo()
app.route('/', main)
app.route('/a', LazyView.create((callback) => splitRequire('./a', callback)))
app.route('/b', LazyView.create((callback) => splitRequire('./b', callback)))
module.exports = LazyView.mount(app, 'body')
function main () {
return html`
<body class="Home">
<h1>home</h1>
<a href="/a">a</a><br>
<a href="/b">b</a>
</body>
`
}
API
The module exposes a Nanocomponent class with two static methods which are used for wrapping your views and choo.mount
.
LazyView.create(callback, loader?)
Accepts a callback and an optional loader view. The callback will be invoked when the returned function is called upon (called immediately in node). The callback in turn should load the required view and relay it's response (or error) back to the caller.
app.route('/page', LazyView.create(function (callback) {
fetchViewSomehow(callback)
}))
The second argument is optional and should be a function or a DOM node which will be displayed while loading. By default the node used to mount the application in the DOM is used as loader (meaning the view remians unchanged while loading).
app.route('/a', LazyView.create(
(callback) => splitRequire('./a', callback),
(state, emit) => html`<h1>Loading view…</h1>`
))
LazyView.mount(app, selector)
Wrapper function for app.mount
. Returns a promise which resolves once the application is ready. This is needed because split-require resolves modules asyncronously.
Promise.resolve(require('./index')).then(function (app) {
var html = app.toString('/a')
})
Extending LazyView
You may extend on LazyView to add a shared framework wrapper, e.g. a header, footer etc.
var html = require('choo/html')
var LazyView = require('choo-lazy-view')
var Header = require('../header')
var Footer = require('../footer')
module.exports = class View extends LazyView {
createElement (state, emit) {
return html`
<body>
${state.cache(Header, 'header')}
${super.createElement(state, emit)}
${state.cache(Footer, 'footer')}
</body>
`
}
}
var choo = require('choo')
var splitRequire = require('split-require')
var View = require('./components/view')
var app = choo()
app.route('/', View.create((callback) => splitRequire('./views/home', callback)))
module.exports = View.mount(app, 'body')
Events
Events are namespaced under choo-lazy-view
and emitted when loading views.
choo-lazy-view:fetch
When fetching a view.
choo-lazy-view:done
When view has been fetched and about to be rendered.