Last active
March 6, 2018 00:59
-
-
Save albertstill/c335ecf61944aa0e2b1e5dfe88b19412 to your computer and use it in GitHub Desktop.
Node streaming html example. Theory is that the assets can be loaded in the browser while the Node server fetches data to render the body.
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
const http = require('http'); | |
const server = http.createServer((req, res) => { | |
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }); | |
/* | |
below is cool because the browser could download assets while we fetch data, | |
BUT there is a huge web breaking caveat, it seems we have to know the HTTP response code at this | |
moment in time. But we don't - what if there is a 500 during fetching? what happens if we actually need to 404? | |
Defaulting to 200 would lead to undesirable outcomes, especially with web scrapers and APM tooling. | |
I think this is the reason an RFC exists on Internet Engineering Task Force (IETF) | |
titled "An HTTP Status Code for Indicating Hints" https://datatracker.ietf.org/doc/rfc8297/ | |
Most notably: | |
"The dilemma here is that even though it is preferable for an origin | |
server to send some header fields as soon as it receives a request, | |
it cannot do so until the status code and the full header fields of | |
the final HTTP response are determined." | |
*/ | |
res.write(` | |
<!DOCTYPE html> | |
<html> | |
<head> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.min.js" type="text/javascript"></script> | |
</head> | |
`); | |
// imagine fetching data then rendering body | |
setTimeout( | |
() => { res.end('<body><h1>Foo bar</h1></body></html>'); }, | |
1000 | |
); | |
}); | |
server.listen(3002); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a cool idea, but I think the status code problem is too much of an issue.
The bundle in your example is from a CDN and it's super popular, so most users will probably already have these bundles cached, but I do agree it would be a huge benefit to users that are using our app bundles, especially because they're so big and we release new fingerprinted versions so often.
I think a better option would be to look at reducing the bundle size rather than guessing that status code and responding.
Maybe there's something I haven't thought about that would make this work though.
You could do it on pages that won't break, like home page etc.