Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should SPA use Ajax or socket.io?

Browsing GitHub repositories, I regularly see SPA implementations that use Ajax but not socket.io. It surprises me as I guess socket.io implementation should be faster (so you don't have to open connection every time you change the route) and therefore provide better user experience. Or do I miss something? Does Ajax-based SPA has any advantages?

like image 797
SiberianGuy Avatar asked Mar 14 '23 05:03

SiberianGuy


1 Answers

This decision solely depends on your requirements, there is no should. It is not even an "either .. or" decision, in some cases it could be a good idea to use an hybrid-approach.

Does Ajax-based SPA has any advantages?

Some thoughts:

  • Reusability: as you may know, socket.io is not just a wrapper around WebSockets. In fact, it uses a custom protocol that is not compatible with other WebSocket implementations - your (web-)clients must support socket.io. When using Ajax on the other hand, you could create a reusable REST-interface that is consumend by different types of applications at the same time, e.g. by your SPA and additionally by a native mobile app.
  • Complexity on both client- and server side: most Javascript-frameworks used for building SPAs provide an excellent out-of-the-box support for Ajax-related communication, and Ajax calls are just plain old HTTP requests that are understood by every web server out there.
  • Performance: as you pointed out, there is no need for socket.io for establishing a new connection on each request. But the thing is, this is also not necessarily the case when using HTTP. Modern browsers make use of a (more or less) smart connection management which might use the same connection for subsequent requests if the idle time between requests is not too long. If you have many concurrent users, this could be more resource-saving than using socket.io, which keeps connections open for a long period of time, even if there is no traffic.
like image 53
alapeno Avatar answered Mar 20 '23 19:03

alapeno