监控背景图片加载纯javascript

Monitoring background image load pure javascript

我有一个简单的代码:

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

我想监控这个 div 加载,当它成功时做一些事情,如果加载时间超过 5 秒做其他事情。

我正在尝试做 :

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

但我相信它只适用于视频和音频。另一方面,它会在完成时得到。

将事件侦听器更改为以下内容:

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

我会做这样的事情(未经测试):

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);

}

然后使用它:

<div id="dk"></div>
<script>
  function onSuccess() { /* do stuff */ }
  function onFailure() { /* do stuff */ }
  BackgroundLoader('d.jpg', 5, onSuccess, onFailure);
</script>