Skip to content

Instantly share code, notes, and snippets.

@jed
Created October 28, 2010 12:12
Show Gist options
  • Save jed/651218 to your computer and use it in GitHub Desktop.
Save jed/651218 to your computer and use it in GitHub Desktop.
send different content based on sideloaded javascript
var urls = {}
require( "http" ).createServer( function( req, res ) {
var url = req.url, timeout
if ( url == "/favicon.ico" ) return res.writeHead( 404 ), res.end()
if ( url in urls ) return urls[ url ]( req, res )
url = "/vapor.js?" + Math.floor( Math.random() * 0xcfd41b9100000 ).toString( 36 )
urls[ url ] = function( req, response ) {
// this is called if the user agent has javascript enabled
clearTimeout( timeout )
delete urls[ url ]
res.end( "<script>document.body.innerHTML = 'rendered by js'</script></body></html>" )
response.writeHead( 204, { "Content-Type": "text/javascript" } )
response.end( "" ) // Copyright (c) 2010 Thomas Fuchs
}
timeout = setTimeout( function() {
// this is called if the user agent does not have javascript enabled
delete urls[ url ]
res.end( "rendered by html</body></html>" )
}, 1000 )
res.writeHead( 200, { "Content-Type": "text/html" } )
res.write( "<html><body><script src='" + url + "'></script>" )
}).listen( 4011 )
@jed
Copy link
Author

jed commented Oct 28, 2010

  1. user sends request to http://localhost:4011/
  2. server writes a unique script tag, waits for it to be fetched
    3a. if the script is not fetched within 1 second, server writes html and ends
    3b. if the script is fetched within 1 second, server writes javascript and ends

@jed
Copy link
Author

jed commented Oct 28, 2010

for some reason this only works in firefox... any ideas why?

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