Detect if objects are loaded [Javascript]

2019-05-26 13:43发布

I was wondering, is there a way to detect if a certain image / div is loaded? For example when i am loading two heavy images and showing a loading sign at the two places the images will later occupy, is there a way to already display the first image when it's loaded while still loading the second one?

3条回答
狗以群分
2楼-- · 2019-05-26 14:00

if an image is done loading, its .complete property switches to true.

查看更多
叼着烟拽天下
3楼-- · 2019-05-26 14:12
myImage.addEventListener('load', function() { ... }, false);

Code inside the above function will be called when the image is finished loading.

查看更多
smile是对你的礼貌
4楼-- · 2019-05-26 14:12

If you are using new Image to preload images, then you can do the following to be notified of then it is loaded

var img = new Image();
img.onload = function() {
    //display the image
    document.getElementById("myDiv").innerHTML = "%3Cimg src='myimg.jpg' alt=''/%3E";
};
img.src = "myimg.jpg";

Remember to set the src after the onload.

查看更多
登录 后发表回答