jQuery ready event not fired on partial page load

Mr AH picture Mr AH · Dec 9, 2009 · Viewed 14.4k times · Source

Here's the situ: A page which contains html and using the jQuery libray and tabs jQuery UI plugin loads another page when some tab is clicked. The problem is that when the page/html is loaded/rendered (let's simplify this and say it's just doing something like $("#myDiv").load(url);), the ready event is not fired because of course the "window" has already loaded and fired the load event. This means that none of the jQuery things I want to do on load (partial load) of the page are executed. The UI.tabs plugin is designed to load pages into other tabs and we can assume that other pages may contain their own jQuery... so there should be some way around this..

I can think of very horrible ways to get over the problem, like have a script block at the bottom of the page being rendered (loaded into a div) which does all things I would do when ready is fired (as you can assume the browser has rendered the page already if the script block is hit). This however is VERY bad practise. Any suggestions?

Answer

Kyle Trauberman picture Kyle Trauberman · Dec 9, 2009

How are you firing the AJAX request to the server? If you're using ASP.NET AJAX, then Brian Hasden's answer is what you are looking for. If you are using jQuery to send the request, then you can either set a call back using the load function.

$(".ajaxLink").load(url, null, function() {
    // code here
});

load() Documentation

or set a global ajaxComplete event that is fired every time an ajax call is complete.

$(document).ajaxComplete(function() {
    // code here
});

ajaxComplete() Documentation