Should I ditch AJAX in client side web development when I’ve got a web-socket open

ajaxwebsockets

I was thinking that maybe I should forget AJAX (HTTP) requests when I've got a web-socket open between client and server, but I decided I should ask here to check if this could be a bad practice for some reason that I'm not thinking of.

Once the socket is open, there's less syntax (often meaning simpler error handling) involved in passing information between client and server with Socket.io (just one example of a web-socket).


Is there some obvious situation where a web-socket (Socket.io for example) isn't going to be capable of handling a functionality that an AJAX request could do easily?

Best Answer

  • If you simply want to remove AJAX in favor of Web Sockets, there must be one problem: what if the client doesn't support Web Sockets?

  • If, on the other hand, you keep AJAX requests if there is no active Web Sockets connection, and use Web Sockets otherwise, then it might make the architecture more difficult to follow. More code written means more code to maintain and more chances to have bugs.

The additional concerns I can think of:

  1. If you have a lot of visitors, Web Sockets server may become quite unresponsive. Keeping AJAX and Web Sockets apart would mean that while notifications may be delayed, the web interface will still feel responsive.

    Taking Stack Exchange as an example, I would hardly notice the Web Sockets delay if my answer is upvoted by somebody at 3:35:17.624 and I see this upvote in my browser only at 3:35:24.501. On the other hand, when I upvote a question and the AJAX request takes 7 seconds, I'll go and check whether my internet connection is ok.

  2. Web Sockets connection takes time to open (two to four seconds on websites I've worked on, 1.5 s. on Stack Exchange). Freezing all AJAX for, say, two seconds every time the page is loaded may not be always acceptable UX-wise.

Finally, it strongly depends on the context and the actual AJAX requests. For example, I would easily imagine all AJAX queries on chat site being moved to Web Sockets (if this is the technology used for chatting there), since the essential features of the website rely any way on Web Sockets. On the other hand, moving AJAX queries to Web Sockets for an e-commerce website (where cart is managed through AJAX) would be really weird in a context where Web Sockets were previously used only for live customer support.