Reputation: 51383
Is there any way I could load an image via javascript and then have a callback fire when it is finished?
Thanks for any ideas.
Upvotes: 1
Views: 786
Reputation: 13557
Have you tried this?
var img = new Image();
img.onload = function(){ alert('loaded'); };
img.src = '/some/image.jpg';
UPDATE
sure you can set the background-image of an element with this. Use the onload event to do whatever you like!
// change background to image - only after image completely loaded
function setBackroundImage(node, imageUrl) {
var img = new Image();
img.onload = function() {
node.style.backgroundImage = imageUrl;
}
img.src = imageUrl;
}
setBackroundImage(document.getElementById('foobar'), '/some/image.jpg');
Upvotes: 3
Reputation: 574
Here is the sample code to handle image load:
var img = document.createElement('img')
img.src = 'https://www.google.com/intl/en_com/images/srpr/logo3w.png'
$(img).load(function(){ alert('Image loaded')})
$('#container').append(img)
Upvotes: 0