0

I am trying to create server side image rotate using jquery+php, when the new image is return by back end I want to preload it and when it is done switch background. Everything works for except preload, during the switch there is couple seconds when the screen is just white.

Here is javascript I have

var current='';

function loadNext(){



 $.ajax({
url: 'rotate.php?next='+current,
context: document.body
}).done(function($resp) {
     current = $resp;

     var imageUrl = 'image.php?next='+current;
     var img = $('<img />');
     img.attr('src', imageUrl);
     img.hide();



     img.load(function(){
      $('body').css('background-image', 'url(' + imageUrl + ')');
      $(this).remove();
     });

     $('body').append(img);

});

}

setInterval(loadNext, 15000);
usearch
  • 65
  • 1
  • 13
  • I see an issue here. You are adding each time the interval rolls. You should use an img object outside the function. This makes youre page heavier and heavier... may be that is the problem. – lalborno Aug 08 '14 at 20:58
  • Do you need to call the img.hide()? if it hides before it loads the next, that maybe the white screen flash. – Yogurt The Wise Aug 08 '14 at 21:08
  • in my opinion your code doesnot make sense. Because you change the background image of body and you also append the same image as a html tag to the body?! Maybe you should really preoload the image using $.ajax and receive the variable from the success closure and use this for the image source. This should be a real preload. – alpham8 Aug 08 '14 at 22:24
  • @lalborno why does it make it heavier, when load is done it removes it from the dom. – usearch Aug 11 '14 at 21:05
  • @YogurtTheWise img I am using only to make browser cache the image, I never want to display it. – usearch Aug 11 '14 at 21:08

1 Answers1

0

I think that you need to append the image when it is loaded like so:

var current='';

function loadNext() {
  $.ajax({
    url: 'rotate.php?next='+current,
    context: document.body
  }).done(function($resp) {
      current = $resp;

      var imageUrl = 'image.php?next='+current;
      var img = $('<img />');
      img.attr('src', imageUrl);
      img.hide();

      var currentImg = $(this);

      img.load(function() {
        $('body').css('background-image', 'url(' + imageUrl + ')');
        currentImg.remove();
        $('body').append(img);
      });

  });

}

setInterval(loadNext, 15000);

I also made sure that the thing that you delete is the one you expect.

Ivaylo Petrov
  • 1,162
  • 9
  • 18
  • I just append to body, so browser will cache it, I don't need the image at all. http://stackoverflow.com/questions/476679/preloading-images-with-jquery something similar – usearch Aug 11 '14 at 21:10