Skip to content

Instantly share code, notes, and snippets.

@cmmartin
Last active August 29, 2015 14:27
Show Gist options
  • Save cmmartin/c738fc34a2873f856e0f to your computer and use it in GitHub Desktop.
Save cmmartin/c738fc34a2873f856e0f to your computer and use it in GitHub Desktop.
An example of streaming html to the browser in ES2015
// An example of streaming html to the browser in ES2015
// inspired by https://github.com/koajs/examples/tree/master/stream-view
// *** Usage ***
// const app = koa()
// app.use(function* () {
// this.type = 'html'
// this.body = new StreamView(this)
// })
// app.listen(3000)
import { Readable } from 'stream'
import co from 'koa/node_modules/co'
export default StreamView
class StreamView extends Readable {
constructor(context) {
super({})
co.call(this, this.render).catch(context.onerror)
}
*render() {
this.push(`
<!DOCTYPE html>
<html>
<head>
<title>Stream city</title>
<style type="text/css"> body { background-color: #dedede; } h1 { font-size: 72px; }</style>
</head>
<body>
`)
this.push(yield this.renderAfterDelay('<h1>Look</h1>', 300)) // async!
this.push(yield this.renderAfterDelay('<h1>I\'m</h1>', 300)) // async!
this.push(yield this.renderAfterDelay('<h1>streaming!</h1>', 300)) // async!
this.push(`
</body>
</html>
`)
this.push(null) // end the stream
}
renderAfterDelay(data, delay) {
return done => setTimeout(() => done(null, data), delay)
}
_read() {}
}
@cmmartin
Copy link
Author

Notice the styles declared in the head render immediately instead of waiting for the body to finish being received. This gives the user the impression that your site is FAST.

20150818-000121_capture

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment