Created
October 28, 2010 12:12
-
-
Save jed/651218 to your computer and use it in GitHub Desktop.
send different content based on sideloaded javascript
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
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 ) |
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
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