Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Monitoring background image load pure javascript

I have a simple code:

<div id="dk" style="background-image: url('d.jpg');"></div>

I would like to monitory this div loading and when it success do something and if the load take more then 5 seconds do otherthing.

I was trying to do :

document.getElementById('dk').addEventListener('loadeddata', function () {
        //do something
    }, false);

But i belive that it works just for vídeos and áudios. Otherhand it will get just when it is complete.

like image 909
Guhh Avatar asked Sep 26 '22 18:09

Guhh


1 Answers

I would do something like this (untested):

function BackgroundLoader(url, seconds, success, failure) {
  var loaded = false;
  var image = new Image();

  // this will occur when the image is successfully loaded
  // no matter if seconds past
  image.onload = function () {
    loaded = true;
    var div = document.getElementById("dk");
    div.style.backgroundImage = "url('" + url + "')";
  }
  image.src = url;      

  setTimeout(function() {
    // if when the time has passed image.onload had already occurred, 
    // run success()
    if (loaded)
      success();
    else
      failure();
  }, seconds * 1000);

}

and then use it:

<div id="dk"></div>
<script>
  function onSuccess() { /* do stuff */ }
  function onFailure() { /* do stuff */ }
  BackgroundLoader('d.jpg', 5, onSuccess, onFailure);
</script>
like image 147
guysigner Avatar answered Oct 11 '22 12:10

guysigner