JQuery: Wait for changed image src attribute to be loaded

时间:2016-10-20 19:00:03

标签: javascript jquery html ajax image

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?

3 个答案:

答案 0 :(得分:1)

$('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>

答案 1 :(得分:0)

Try this:

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

OR

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

答案 2 :(得分:0)

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)