Markus Weninger
Markus Weninger

Reputation: 12668

JQuery: Wait for changed image src attribute to be loaded

I'm completely new to JavaScript and JQuery, and I have the following problem I was not able to solve by reading other SO Q&As:

I have a function that GETs the path to an image (/API/currentImage) and wants to change the src attribute of an img, and then repeat itself after 1 second. So far, so good, the following code works. But: If the image is large, the GET for the image itself may take rather long (longer than 1 second). So I would like to execute setTimeout not when the AJAX requests are finished, but when the image is finally loaded ("The image loading after $('img').attr("src", r1[0]) has finished").

loadImg = function() {
  $.when(
    $.ajax({
      url: "/API/currentImage"
    }),
    $.ajax({
      url: "/API/currentId"
    })
  ).done(function(r1, r2) {
    $('#iid').text(r2[0])
    $('img').attr("src", r1[0])
    window.setTimeout(function () {
      loadImg()
    }, 1000)
  })
}

How can I achieve that?

Upvotes: 1

Views: 2716

Answers (3)

Markus Weninger
Markus Weninger

Reputation: 12668

Similar to @Fribu's answer, I now implmented it using the one function, instead of using on:

$('img').one("load", function () {
    window.setTimeout(function () {
        loadImg()
    }, 1000)
}).attr("src", newSrc)

Upvotes: 1

Alexander_F
Alexander_F

Reputation: 2877

$('img').on("load",...)

should to the trick.

ADDED:

<img />

  <div id="hi"></div>
  <script src="https://code.jquery.com/jquery-3.1.1.js"></script>
  <script>

    $(document).ready(function() {
      var i = 0;
      var h = $("#hi");

      $("img")[0].onload = function() {
        //alert("done");
        i++;
        h.html(i);
      }


      $("img").attr("src", "http://cdn.sstatic.net/Sites/stackoverflow/img/sprites.svg?v=8c1c8cba242e")
    });

  </script>

Upvotes: 2

gschambial
gschambial

Reputation: 1391

Try this:

$('img').attr("src", r1[0]).done(function(){
    window.setTimeout(function () {
      loadImg()
    }, 1000)
});

OR

$('img').load(function () {
        window.setTimeout(function () {
          loadImg()
        }, 1000)
    });

Upvotes: 0

Related Questions