Skip to content

Instantly share code, notes, and snippets.

@jrf0110
Forked from prestonp/incremental.md
Last active August 29, 2015 14:20
Show Gist options
  • Save jrf0110/908066c01c9dec12e6c0 to your computer and use it in GitHub Desktop.
Save jrf0110/908066c01c9dec12e6c0 to your computer and use it in GitHub Desktop.

In many websites, there are static portions of the page such as the navigation or header that rarely change. If we could deliver the markup for navigation, the experience would feel a bit snappier while the rest of the page is generated.

Try running this snippet in node and visit localhost:3000/incremental and localhost:3000/blocking. These are pretty trivial examples but we could cache and immediately send the nagivation bar and <head> elements for every request.

var http = require('http');
var port = process.env.port || 3000;
var server = http.createServer();
var log = function(req) {
console.log(req.method + ' ' + req.url);
};
var router = {
'/progressive': function(req, res) {
res.statusCode = 200;
res.setHeader("Content-Type", "text/html");
res.write([
'<html>'
, ' <head>'
, ' <script src="//code.jquery.com/jquery-1.11.2.min.js"></script>'
, ' <style type="text/css">'
, ' html, body {'
, ' background: red;'
, ' font-family: sans-serif;'
, ' }'
, ' </style>'
, ' </head>'
, ' <body>'
, ' <h1>Hello world</h1>'
].join('\n'));
setTimeout(res.write.bind(res, '<h1>blah</h1>'), 5000);
setTimeout(res.write.bind(res, [
'<style type="text/css">'
, ' html, body {'
, ' background: blue;'
, ' }'
, '</style>'
].join('\n')), 8000);
setTimeout(res.write.bind(res, '<h1>blah</h2>'), 10000);
setTimeout(res.write.bind(res, '</body></html>'), 15000);
setTimeout(res.end.bind(res), 20000);
},
'/blocking': function(req, res) {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
setTimeout(function() {
res.write('one<br>two<br>three<br>four<br>');
res.end();
}, 4000);
}
};
var route = function(req, res) {
log(req);
if (req.url in router) {
router[req.url].call(router, req, res);
} else {
res.write('Could not find route ' + req.url);
res.statusCode = 404;
res.end();
}
};
server.on('request', route);
server.listen(port, function() {
console.log('listening on port', port);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment