Skip to content

Instantly share code, notes, and snippets.

@prestonp
Last active August 29, 2015 14:19
Show Gist options
  • Save prestonp/c91559bce9dc89a3539a to your computer and use it in GitHub Desktop.
Save prestonp/c91559bce9dc89a3539a to your computer and use it in GitHub Desktop.
progressive rendering

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></head><body><h1>Hello world</h1>');
setTimeout(res.write.bind(res, '<h1>blah</h1>'), 5000);
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