Skip to main content

Excessive AJAX requests

When loading any page on your site, pay attention to how many AJAX calls are being made to the server (especially for code that executes on every page).

It is better to have the minimum number of requests necessary to get the data you need, rather than having them split up - which can result in a kind of inner conflict where code design is concerned.

Design vs performance considerations

Suppose a page has the following 5 AJAX requests that are fired on every page load when a user is logged in:

  • Load unread message count
  • Load unread notification count
  • Load first X unread messages
  • Load first X unread notifications
  • Load user information

From a code maintenance perspective, it's often good to have functions separated out like this, so that if one breaks the others are not also broken. The problem is that, from a performance and networking perspective, the client is making 5 requests to the server when only one was needed. This means two things:

More server requests = higher server load

Not that this should come as any surprise, but having lots of AJAX requests constantly bombarding your servers puts them under a lot of pressure, due to the increased network and request overhead.

Race conditions on page load

In certain cases, your AJAX requests are going to be updating the page when they receive a response (for instance, to show the unread message count). While for some functions that doesn't matter, for others that change the page layout or add elements to a page, it can make for a "janky" looking page - because it doesn't load consistently, owing to the fact that which order they will execute in depends on which AJAX requests finish first, and that isn't always going to be the same order.

Downsides to amalgamating AJAX requests

While getting your data in as few AJAX requests as possible reduces server load, there is a potential problem with this approach as well. 

On pages where you want data to be loaded in an "as it becomes available" fashion, having everything be retrieved in one AJAX request can make for an awkward-looking frontend: the page is empty of content, and then suddenly full of content, but nothing in between. This can result in a page that looks like it takes long to load, or an uncomfortable "jerking" of the page when a load of content all appears at once.