Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if background img failed to load?

As title says. I want to be able to determine if a background img failed to load. I looked around and seen loads of information but sadly cant get any of them to work for me.

I seen a pretty good one describing to use a plugin called waitForImages located: https://github.com/alexanderdickson/waitForImages

I cant seem to get the failed to load work. Now, if someone has a better way im all open! As long as i can get an alert to say it failed. I pushed in a fake URL so it should come back with link not working.

Code:

$("#cover-art").css("background-image", 'url("/assets/img/cover-adio.png")');

$('#cover-art').waitForImages(function() {
    alert('All images have loaded.');
}, function(loaded, count, success) {
   alert(loaded + ' of ' + count + ' images has ' + (success ? 'loaded' : 'failed to load') +  '.');
   $(this).addClass('loaded');
});
like image 255
William Avatar asked Nov 08 '25 21:11

William


1 Answers

I don't know if there is a way to check given url exists with client side javascript. But you can try this trick.

    <!DOCTYPE html>
    <html>
    <head>
    	<title></title>
    </head>
    <body>

    <div id="mydiv" style="background-image:url('foo.png')">
      <img id="foo_img" src="foo.png" style="display:none;">
      
      <p>Status:<span id="result"></span></p>
    </div>

    </body>
    <script type="text/javascript">
    var imgtowatch = document.getElementById("foo_img");
    var events = ["load", "error"];

    events.forEach(function(ev){
    imgtowatch.addEventListener(ev, function(){
      document.getElementById("result").innerHTML = ev;
    });
    });
    </script>
    </html>

then try with

`style="background-image:url('http://cdn.sstatic.net/stackexchange/img/logos/so/so-logo.png')` 

and

src='http://cdn.sstatic.net/stackexchange/img/logos/so/so-logo.png' 
like image 187
marmeladze Avatar answered Nov 10 '25 16:11

marmeladze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!