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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With