Category Archives: AJAX

WHY DO WE USE WEBSOCKETS WHEN AJAX CAN DO THE WORK?

Why do we use WebSockets when AJAX can do the work?

There are a few reasons:

Bi-directional communication.If your service is real-time you will typically not want to make a request and wait for a response; you want a response whenever the server is ready to send one. This isn’t possible with AJAX.

Less server overhead. The alternative to WebSockets are HTTP polling techniques (short- or long-polling) or Server Sent Events. Polling techniques are often inefficient or have a larger server burden than WebSockets. Server Sent Events aren’t standardized across browsers.

Smaller request frames.¬†While less of a problem if you’re using HTTP/2, a lot of HTTP requests come with a lot of overhead that you likely don’t want/need for standard requests. Websockets use much smaller frames for communication, resulting in slightly faster communication.

EXPLAIN “DEFERREDS”?

Explain “Deferreds”?

Deferreds

  • In their simplest form, deferreds allow you to specify what will occur when a computation/task completes or fails. jQuery’s specific implementation allows you to register callback functions that will run if a deferred resolves successfully, if it is rejected with errors, or if it is notified of some “progress” towards a resolved state (more on that later).
  • The “Deferred” pattern describes an object which acts as a proxy for some unit of computation that may or may not have completed.
  • The pattern can apply to any asynchronous process: AJAX requests, animations or web workers to name a few.

Important to understand:

  • Deferreds can be passed around indefinitely, and callbacks can continue to be added during the entire lifetime of the deferred object.
  • The key to this behavior is callbacks registered with the deferred will run immediately if the deferred is already resolved.
  • You don’t need to worry if the asynchronous unit of computation (e.g. an AJAX request) is finished or not.