0
<div class="content">Some original Text<img src="someImage"></div>

$.ajax('someAjaxUrl', function(data){
    $('content').html(data);
})

I'm using some codes similar to above to get content from server and display it in the content area. The actual content contains lots of images and text, so after the ajax request is completed and the HTML has been changed, it still takes some time to render all the images. I'm trying to catch the event when all the new contents have been fully loaded including the images:

$.ajax('someAjaxUrl', function(data){
    $('content').html(data);
    $('content')[0].addEventListener('load',function(){
      // Do something
    })
})

But this seems not working. Is this possible?

shenkwen
  • 3,536
  • 5
  • 45
  • 85

1 Answers1

0

Yes. If you run:

$(document).ready(function(){
// AJAX, etc in here ...
});

You can do anything inside the function WHEN the document has loaded.

Edit:

If you're running the AJAX after the page had already loaded, you can place them into something like this:

<div id="loaded" style="display: none">
<img src""/>
<p>Whatever you want in here.</p>
<img src""/>
<img src""/>
<img src""/>
</div>

Then in your jQuery:

$('#loaded img').load(function(){
$('#loaded').show()
});
Filthy_Rich
  • 666
  • 5
  • 20
  • Put that within your AJAX request and the 'loaded' div will only be displayed once the images are loaded. – Filthy_Rich Aug 15 '15 at 03:47
  • You'd essentially be preventing the user from seeing the loading of images, they'd be displayed when loaded. – Filthy_Rich Aug 15 '15 at 03:57
  • Sorry, I defined loaded as a class. Edited. – Filthy_Rich Aug 15 '15 at 04:03
  • On this page http://api.jquery.com/load-event/ it says 'load' event "Can cease to fire for images that already live in the browser's cache". It is a little hard to test but I am wondering if the users click back and forth then there will be some images that have already been in the cache, which will make the 'load' event cease to fire. This is problematic because I will hide the new content until the 'load' event fires, any solution for this? – shenkwen Aug 15 '15 at 12:45
  • What is the most ideal outcome for you when the user loads the page? I thought we were just preventing the user from seeing the rendering of images? – Filthy_Rich Aug 15 '15 at 13:01
  • I personally would add an animated load in screen that disappears when the images have loaded – Filthy_Rich Aug 15 '15 at 13:03
  • If I've helped at all could you vote my suggestion up please. – Filthy_Rich Aug 15 '15 at 13:36