最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Monitoring background image load pure javascript - Stack Overflow

programmeradmin8浏览0评论

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);
发布评论

评论列表(0)

  1. 暂无评论