166

我想知道图像何时完成加载。有没有办法通过回调来做到这一点?

如果没有,有没有办法做到这一点?

4

10 回答 10

187

.complete+ 回调

这是一种符合标准的方法,没有额外的依赖项,并且无需等待:

var img = document.querySelector('img')

function loaded() {
  alert('loaded')
}

if (img.complete) {
  loaded()
} else {
  img.addEventListener('load', loaded)
  img.addEventListener('error', function() {
      alert('error')
  })
}

来源:http ://www.html5rocks.com/en/tutorials/es6/promises/

于 2014-06-13T08:48:11.587 回答
82

Image.onload()通常会起作用。

要使用它,您需要确保在设置 src 属性之前绑定事件处理程序。

相关链接:

示例用法:

    window.onload = function () {

        var logo = document.getElementById('sologo');

        logo.onload = function () {
            alert ("The image has loaded!");		
        };

        setTimeout(function(){
            logo.src = 'https://edmullen.net/test/rc.jpg';         
        }, 5000);
    };
 <html>
    <head>
    <title>Image onload()</title>
    </head>
    <body>

    <img src="#" alt="This image is going to load" id="sologo"/>

    <script type="text/javascript">

    </script>
    </body>
    </html>

于 2008-11-11T05:19:46.893 回答
21

You can use the .complete property of the Javascript image class.

I have an application where I store a number of Image objects in an array, that will be dynamically added to the screen, and as they're loading I write updates to another div on the page. Here's a code snippet:

var gAllImages = [];

function makeThumbDivs(thumbnailsBegin, thumbnailsEnd)
{
    gAllImages = [];

    for (var i = thumbnailsBegin; i < thumbnailsEnd; i++) 
    {
        var theImage = new Image();
        theImage.src = "thumbs/" + getFilename(globals.gAllPageGUIDs[i]);
        gAllImages.push(theImage);

        setTimeout('checkForAllImagesLoaded()', 5);
        window.status="Creating thumbnail "+(i+1)+" of " + thumbnailsEnd;

        // make a new div containing that image
        makeASingleThumbDiv(globals.gAllPageGUIDs[i]);
    }
}

function checkForAllImagesLoaded()
{
    for (var i = 0; i < gAllImages.length; i++) {
        if (!gAllImages[i].complete) {
            var percentage = i * 100.0 / (gAllImages.length);
            percentage = percentage.toFixed(0).toString() + ' %';

            userMessagesController.setMessage("loading... " + percentage);
            setTimeout('checkForAllImagesLoaded()', 20);
            return;
        }
    }

    userMessagesController.setMessage(globals.defaultTitle);
}
于 2008-11-11T06:12:33.120 回答
14

jquery 的生命太短暂了。

function waitForImageToLoad(imageElement){
  return new Promise(resolve=>{imageElement.onload = resolve})
}

var myImage = document.getElementById('myImage');
var newImageSrc = "https://pmchollywoodlife.files.wordpress.com/2011/12/justin-bieber-bio-photo1.jpg?w=620"

myImage.src = newImageSrc;
waitForImageToLoad(myImage).then(()=>{
  // Image have loaded.
  console.log('Loaded lol')
});
<img id="myImage" src="">

于 2018-01-11T13:38:20.510 回答
12

您可以在 jQuery 中使用 load() 事件,但如果图像是从浏览器缓存中加载的,它不会总是触发。这个插件https://github.com/peol/jquery.imgloaded/raw/master/ahpi.imgload.js可以用来解决这个问题。

于 2011-02-06T12:05:55.990 回答
4

这是 jQuery 等价物:

var $img = $('img');

if ($img.length > 0 && !$img.get(0).complete) {
   $img.on('load', triggerAction);
}

function triggerAction() {
   alert('img has been loaded');
}
于 2017-03-22T08:43:14.277 回答
3

不适合 2008 年问这个问题,但这些天这对我来说效果很好:

async function newImageSrc(src) {
  // Get a reference to the image in whatever way suits.
  let image = document.getElementById('image-id');

  // Update the source.
  img.src = src;

  // Wait for it to load.
  await new Promise((resolve) => { image.onload = resolve; });

  // Done!
  console.log('image loaded! do something...');
}
于 2020-06-04T00:42:19.407 回答
2

如果目标是在浏览器渲染图像后设置 img 样式,您应该:

const img = new Image();
img.src = 'path/to/img.jpg';

img.decode().then(() => {
/* set styles */
/* add img to DOM */ 
});

因为浏览器首先loads the compressed version of image,然后decodes it,最后paints它。因为在浏览器具有img 标签paint后,您应该运行您的逻辑没有任何事件。decoded

于 2020-04-01T12:39:53.223 回答
0

这些函数将解决问题,您需要实现该DrawThumbnails函数并有一个全局变量来存储图像。我喜欢让它与具有ThumbnailImageArray作为成员变量的类对象一起工作,但我很挣扎!

称为addThumbnailImages(10);

var ThumbnailImageArray = [];

function addThumbnailImages(MaxNumberOfImages)
{
    var imgs = [];

    for (var i=1; i<MaxNumberOfImages; i++)
    {
        imgs.push(i+".jpeg");
    }

    preloadimages(imgs).done(function (images){
            var c=0;

            for(var i=0; i<images.length; i++)
            {
                if(images[i].width >0) 
                {
                    if(c != i)
                        images[c] = images[i];
                    c++;
                }
            }

            images.length = c;

            DrawThumbnails();
        });
}



function preloadimages(arr)
{
    var loadedimages=0
    var postaction=function(){}
    var arr=(typeof arr!="object")? [arr] : arr

    function imageloadpost()
    {
        loadedimages++;
        if (loadedimages==arr.length)
        {
            postaction(ThumbnailImageArray); //call postaction and pass in newimages array as parameter
        }
    };

    for (var i=0; i<arr.length; i++)
    {
        ThumbnailImageArray[i]=new Image();
        ThumbnailImageArray[i].src=arr[i];
        ThumbnailImageArray[i].onload=function(){ imageloadpost();};
        ThumbnailImageArray[i].onerror=function(){ imageloadpost();};
    }
    //return blank object with done() method    
    //remember user defined callback functions to be called when images load
    return  { done:function(f){ postaction=f || postaction } };
}
于 2012-10-24T16:43:41.190 回答
-3

如果你使用 React.js,你可以这样做:

render() {

// ...

<img 
onLoad={() => this.onImgLoad({ item })}
onError={() => this.onImgLoad({ item })}

src={item.src} key={item.key}
ref={item.key} />

// ... }

在哪里:

  • - onLoad (...) 现在将调用如下内容: { src: " https://......png ", key:"1" } 你可以使用它作为 "key" 来了解哪些图像正确加载,哪个不正确。
  • - onError(...) 它是相同的,但对于错误。
  • - 对象 "item" 类似于 { key:"..", src:".."} 您可以用来存储图像的 URL 和键,以便在图像列表中使用。

  • 于 2018-05-28T15:30:52.570 回答