I am using .load() extensively for AJAX content. It’s great but I would like it if it did a little more:
-
If, in response to user actions, I make multiple calls to
.load()on the same div, I can end up with the wrong data in the div. This happens when an earlier request is slower to callback than a later one. I need something to reject out-of-date callbacks -
It would be nice if
.load()added a CSS class to the target… and removed that class after callback completed.
Is there a library or plugin for jQuery that offers such functionality? Or can it be done in so few lines that it’s not worth a plugin?
It’s super easy to create your own plugin that prevents multiple concurrent requests. Here’s a simple plugin that intercepts AJAX calls, keeps a list of outstanding requests and aborts them when a new one comes in:
You can easily extend this so that it cancels earlier requests that are still outstanding when a request completes instead of when one is queued; to do this you will also need to store a timestamp with each request.
You can also use jQuery’s
.ajaxStart()and.ajaxStop()to trivially automate toggling a “loading” class, for example: