Last active
August 29, 2015 14:27
-
-
Save cmmartin/c738fc34a2873f856e0f to your computer and use it in GitHub Desktop.
An example of streaming html to the browser in ES2015
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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() {} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.