Martijn
Martijn

Reputation: 3754

jquery empty() parallel with ajax call

I have a jQuery-based page which replaces a lot of the content from the server. There are a couple of things that are slow in this; the AJAX call to load the new content and the .empty() calls to remove and unbind previous content.

Currently the script does an AJAX call to the server and, upon success, removes old content and builds new content.

Since the script is basically doing nothing while waiting for the AJAX call to finish, couldn't I use this time to do the slow .empty() calls?

I was thinking of something like the following:

  1. Start the AJAX call.
  2. Run all the .empty() calls.
  3. When both 1 and 2 are completed, build new content.

Steps 1 and 2 are easy, I understand step 3 would require delegates, which I'm not familiair with. How should I do this (assuming it's possible)?

Upvotes: 0

Views: 56

Answers (1)

Nate
Nate

Reputation: 322

Kevin B is correct for most cases, however, there may be some theoretical scenarios where that might not work. For example, if you were on a corporate LAN connection with fiber internet within reasonable distance to the networking equipment, and if you had a large chunk of html to remove from the DOM using the .empty() command, the response from the server might be returned before the command has finished executing.

Although, that will probably never be the case, I would suggest that you look into using jQuery's $.deferred() commands (http://api.jquery.com/category/deferred-object/) or using webworkers to concurrently run multi-threaded tasks ( see http://www.html5rocks.com/en/tutorials/workers/basics/#toc-introduction-jsconcurrency for more info).

Upvotes: 1

Related Questions