fancy
fancy

Reputation: 51383

A script to preload images and then fire a callback when they are?

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

Answers (2)

rodneyrehm
rodneyrehm

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

Ivan Kolodyazhny
Ivan Kolodyazhny

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

Related Questions