Monitoring background image load pure javascript - Stack Overflow

I have a simple code:<div id="dk" style="background-image: url('d.jpg');&qu

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 plete.

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 plete.

Share Improve this question asked Jan 6, 2016 at 19:29 GuhhGuhh 4087 silver badges15 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

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>

Change the event listener to the following:

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744830989a4596079.html

相关推荐

  • Monitoring background image load pure javascript - Stack Overflow

    I have a simple code:<div id="dk" style="background-image: url('d.jpg');&qu

    2天前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信