The problem with events on an AJAX-heavy page
I have an asp page that uses jQuery ajax to load item counts into a heap div
after the page has loaded.
It works great in FireFox and with clients that have a small number of groups.
For a small number of clients that have many groups (500+), I get an error in IE. The ajax calls seem to work synchronously because click events won't be logged until every ajax call returns.
Series of ajax requests is just 1 request for most clients. It only breaks down into a few requests for clients with a VERY large number of groups.
Now I saw a bug where functions are $("a").click
not linked if links are added after the DOM has loaded. Links that don't work aren't loaded by AJAX, they don't fall into this category.
Here's the pseudocode:
ready()
{
// count the number of groups that this user has, adding the ids to a list
if( count < 50 )
{
runAjax();
}
else
{
// this calls the ajax request on groups of 50 ids
// it pauses briefly after each request by using setTimeout to call the next
runAjaxRecursively();
}
}
And here is the ajax request:
// run the HTTPRequest
$.ajax({
async: true,
type: "POST",
url: "emailcatcount.asp?idList="+idList,
data: "idList="+idList,
dataType: "html",
success: function(html) { // blah blah blah }
});
Anyway, the code works fine, so please treat any errors as typos. The only problem is, in IE, click events won't fire until every single ajax call returns.
Does anyone know why this is happening? Note that I am setting async
to true.
Does this have anything to do with how the jQuery handled event is handled in IE?
I got confused and spent a few days on this so any ideas are appreciated.
source to share
Your problem is that you are not providing browser time, try adding a little setTimeout in a recursive loop to give the browser time to handle other events, remember you only have one thread to play. You would be better off trying to make just one call and use jtemplates along with json to process data and render markup instead of returning heavy html.
Also the error you are talking about is not an error, jQuery only binds handlers for elements that exist at the time. If you have dynamic content, you're better off using Delegation Delegation to handle click events on dynamic elements. This way you are not explicitly binding each element, but rather binding the click event to a static container. Then you can query event.target to see if it was one of your desired elements that raised the event, and if so, handle the desired behavior. The advantage is that you don't burden the house with a lot of related events and dynamic content.
source to share