When writing web based apps a recurring problem is updating page contents in response to server side events. A classical pattern to solve it is to do periodic pooling of the server using XMLHttpRequests, however this often leads to making far more HTTP requests than what is really needed. It would be best to be able to originate the update from the server. Emerging technologies such as HTML5 websockets may provide a neat solution in the future, but until they become widely supported by all major browsers your path will be filled of all sort of "workarounds" to emulate the websockets on all those still catching-up. However a simple solution may be at hand in some particular cases: enter the world of html streaming.
The pattern is relatively simple:
- Upon a request an html page is sent to the browser,
- but instead of closing the connection, you keep it open.
- Then you can append script tags that are evaluated as soon as they arrive to the browser, updating the page content.
Let's start with the HTML, save the following as index.html:
<html> <head> </head> <body> <ul id="log"> </ul> </body> </html>
Here we defined a constructor function, webPush that takes the argument "id" and returns an object. We place this script in the head of our html. Later, in the body, just after adding the UL that we are going to use to display the incoming data, we create an instance of the object, pointing to our target UL id: log (lines 10-15 ):
At the end of the method addLi, a call to removeScript prevents unnecessary accumulation of the script snippets after the new list items are appended.
We are now set to start. All that is remaining is to get the server to send scripts snippets making calls on our object:
Let's look at a basic web server that completes our pattern:
The server relies on a basic.LineReceived-based protocol: WebPUSH. Upon receiving the first line of the request, we send the html to the browser (lines 15-26). Then a call to logTime sends the first data stream and registers a timer to repeat the call in 2 seconds (lines 29-31).
That's it! Save the server. Run it, point your browser to http://localhost:8080 and watch the timestamps appear every 2 seconds