0

I use a function to check if an image is online. If so it will be attached as a background of its parent container. The Js-part is incorporated in the head. There are some secondary js-files below the fold. I think this makes that the image is loaded before the checking-alive function is triggered. The result is the image is not checked and attached to the parent div. How can I make sure the function is triggered early on?

(function($) {
  $("figure.card-head img").on({
    load: function() {
      var source = $(this).attr("src");
      $(this).closest("figure").css("background-image", "url(" + source + ")");
      $(this).remove();
    },
    error: function() {
      $(this).parent().remove();
    }
  });
)(jQuery);
<div class="col-4_sm-12">
        <div class="thecard">
            <figure class="card-head">
                <img id="c131969" src="http://beitostolen.no/webcam/sentrum.jpg" />
            </figure>
            <div class="card-caption">
                <a href="#like" class="like-btn fa fa-thumbs-o-up"></a>
                       <span class="date">Thursday, July 16, 2015</span>
                    <h3>Beitostolen centre</h3>
                    <p></p>
                    <p>   </p>
            </div>
            <a class="card-outmore" href="/review/beitostolen/131969/">
                <i class="outmore-icon fa fa-angle-right"></i>
            </a>
        </div>
    </div>
Siyual
  • 16,415
  • 8
  • 44
  • 58
Mark Henry
  • 2,649
  • 7
  • 40
  • 48
  • Possible duplicate of [Check if image exists on server using JavaScript?](http://stackoverflow.com/questions/18837735/check-if-image-exists-on-server-using-javascript). What you are trying to do is just wrong. Check the duplicate question how it should be done correctly. – smnbbrv Dec 11 '15 at 19:54
  • that is no option 'cause the image is on a third party server. Moreover, If the image does not fail you are making two requests. – Mark Henry Dec 12 '15 at 07:22
  • you are not making two requests, the browsers are smart enough to avoid it. Also you should have a look on a second answer there http://stackoverflow.com/a/18837818/1990451 which is more correct especially for your case – smnbbrv Dec 12 '15 at 08:16

0 Answers0