Maksim Vi.
Maksim Vi.

Reputation: 9225

jQuery load-event after replaceWith

i'm trying to ajax load some content and then replace existing content on the page with the newly downloaded content. The problem is that I need to bind load(handler(eventObject)) event for replaced data. I need that to trigger when all images are loaded. Here is what I have so far:

$("#mainContentHolder").live("load", function(){ 
   alert("images loaded!") 
});

$.get("content.htm", function(data){
    $("#mainContentHolder").replaceWith(data);
    alert("content is loaded!");
});

I see an alert when the content is loaded, but it happens before images are loaded and alert on images load never happens (I also tried bind() instead of live() before). Does anyone know a fix for that?

Upvotes: 1

Views: 1951

Answers (2)

bozdoz
bozdoz

Reputation: 12860

Is it possible to put the $.get into the live load function?

$("#mainContentHolder").live("load", function(){ 
   alert("images loaded!");
$.get("content.htm", function(data){
    $("#mainContentHolder").replaceWith(data);
    alert("content is loaded!");
});
});

Upvotes: 0

Ender
Ender

Reputation: 15221

This may or may not be your problem, but it looks like the container you have attached your image load function to is being replaced when you load the ajax content:

$("#mainContentHolder").live("load", function(){ //you are attaching to current and future '#mainContentHolder' elements
   alert("images loaded!") 
});

$.get("content.htm", function(data){
    $("#mainContentHolder").replaceWith(data);  //'#mainContentHolder' element is replaced with something else
    alert("content is loaded!");
});

Not sure what content is coming back from your AJAX call, but if it doesn't have a #mainContentHolder element, there will be nothing for your image load event handler to attach to.

If that's not it, there's also this bit: (from http://api.jquery.com/load-event/)

It is possible that the load event will not be triggered if the image is loaded from the browser cache. To account for this possibility, we can use a special load event that fires immediately if the image is ready. event.special.load is currently available as a plugin.

Hopefully one of those will help you out.

Upvotes: 2

Related Questions