我有一个简单的代码:
我想监视此div加载,如果加载成功,则执行某些操作,如果加载时间超过5秒钟,则执行其他操作。
我正在尝试做:
document.getElementById('dk').addEventListener('loadeddata', function () { //do something }, false);
但是我相信它仅适用于视频和áudios。否则,它将在完成时获得。
我会做这样的事情(未经测试):
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); }
然后使用它: