一个脚本来预加载图像然后触发回调?

时间:2012-02-13 17:06:30

标签: javascript image

有没有什么方法可以通过javascript加载图像然后在完成时回调一下?

感谢您的任何想法。

2 个答案:

答案 0 :(得分:3)

你试过这个吗?

var img = new Image();
img.onload = function(){ alert('loaded'); };
img.src = '/some/image.jpg';

<强>更新

确保您可以使用此设置元素的背景图像。使用onload事件做你喜欢的事情!

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

答案 1 :(得分:0)

以下是处理图像加载的示例代码:

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)
相关问题