3

I am new to javascript and trying on a slider.My problem is similar to the below question jquery .attr() with callback?. If the flow is synchronous, shouldnt the display be delayed till the source is fully loaded rather than showing the old image

$('.container').fadeOut(100, function(){
     console.log("before");
     $('.container > img').attr('src', 'image src');
     $('.container').show();
     console.log("after");
 });

I could see both the logs in the console before the new image gets loaded.. Can anyone pls explain...Pls pardon if the question is naive I am trying to get hold of the concept..

Community
  • 1
  • 1
user1776573
  • 271
  • 1
  • 2
  • 12

3 Answers3

4

The moment you call $('.container > img').attr('src', 'image src'); , a request is made to server to load the image. It takes time to load the image hence the delay.

But if you look closely, the line is executed perfectly. The reason you see console entry before image loads is because the image takes time to load

U.P
  • 7,152
  • 6
  • 32
  • 58
2

Use .load event listener which will be trigger when the image is loaded

$('.container > img').attr('src', 'image src').load(function(){
  $('.container').show();
});
Romaindr
  • 301
  • 1
  • 7
2

The javascript is synchronous, but the problem is that setting the src attribute is not the same as displaying the image. Once you set the src, you dispatch the browser to start loading the image, then the execution of your script continues. If you want code to execute after the image has been loaded, you'll have to attach the call to the image's onload event.

In jQuery use the load function:

$('.container > img').attr('src', 'image src').load(function(){
   // Stuff to do after the image has been loaded
});
Marcus
  • 298
  • 2
  • 4
  • however make sure you bind to the load event before setting it's src. – Kevin B Aug 29 '13 at 14:16
  • @user1776573 IE yes, Ie7 specificially, not sure. Basically, IE executes the load event synchronously, resulting in it happening before the load event is bound to if the image is cached. – Kevin B Aug 30 '13 at 14:07