Search code examples
javascriptiframexmlhttprequestcomet

longpoll XHR vs iframe


I'm implementing typical server-push (comet) application. I'm choosing between two options: the longpoll XHR and iFrames. What are pros and cons of these? I know about the cross-site restrictions and that iFrame is pretty heavyweight component... are there any other differences? For example the "reliability" of the transport or level of control over the component? What do you think, is there a single right answer which approach is better or there are use cases for both of them?

Thanks in advance.

P.S. I got a pretty good working XHR implementation, but I want to consider the alternatives.


Solution

  • you should use socket.io or an equivalent library. It supports both ways you mention and more:

    http://socket.io/#transports

    However, let's assume your using an appropriate abstraction layer, and now want to decide which transport to use. :)

    IMO, the deal-breaker for iframes is error handling. The continuously loading iframe technique makes it much harder to do error handling. You're not informed via a convenient event of 404s or timeouts, so you have to set an interval in the JavaScript to watch for errors.

    Supposedly iframes have less overhead than making a new XHR/HTTP request to reconnect after every message, but when I tried it all I saw was increased memory overhead on my server and zero responsiveness improvement; probably it depends on your choice of backend.

    Another interesting factoid is that browsers are limited to two concurrent requests to a server by the standard, but Mozilla made an exception for XHR only:

    https://developer.mozilla.org/en/XMLHttpRequest

    When you're making long requests, the 2 connection limit is really important: if you tie up both pipes, nothing else will be able to get through! You have to be care to set up a single channel that all the code on the page shares. But on Firefox, you now get some wiggle room, if and only if you use XHR.

    Iframes do have the advantage of being able to make cross domain requests.