39

读了别人的问题后我想

window.onload=...

会回答我的问题。我已经尝试过了,但是它会在页面加载的那一刻(而不是在图像加载之后)执行代码。

如果有任何区别,则图像来自 CDN 并且不是相对的。

有人知道解决方案吗?(我没有使用 jQuery)

4

8 回答 8

62

这是现代浏览器的快速破解:

var imgs = document.images,
    len = imgs.length,
    counter = 0;

[].forEach.call( imgs, function( img ) {
    if(img.complete)
      incrementCounter();
    else
      img.addEventListener( 'load', incrementCounter, false );
} );

function incrementCounter() {
    counter++;
    if ( counter === len ) {
        console.log( 'All images loaded!' );
    }
}

加载所有图像后,您的控制台将显示“所有图像已加载!”。

这段代码的作用:

  • 从文档中加载变量中的所有图像
  • 循环浏览这些图像
  • 为每个图像上的“加载”事件添加一个侦听器以运行该incrementCounter函数
  • incrementCounter增加计数器
  • 如果计数器已达到图像的长度,则意味着它们都已加载

以跨浏览器的方式拥有这段代码不会那么难,它只是像这样更干净。

于 2012-06-17T13:37:06.357 回答
53

想要单线?

Promise.all(Array.from(document.images).filter(img => !img.complete).map(img => new Promise(resolve => { img.onload = img.onerror = resolve; }))).then(() => {
    console.log('images finished loading');
});

相当向后兼容,甚至可以在 Firefox 52 和 Chrome 49(Windows XP 时代)中使用。但是,不在 IE11 中。

如果要缩小图像列表,请替换document.images为 eg 。document.querySelectorAll(...)

为简洁起见,它使用onloadonerror。如果元素的这些处理程序img也设置在其他地方(不太可能,但无论如何),这可能与页面上的其他代码冲突。如果您不确定您的页面不使用它们并且想要安全,请将该部分替换img.onload = img.onerror = resolve;为更长的部分:img.addEventListener('load', resolve); img.addEventListener('error', resolve);.

它也不会测试是否所有图像都已成功加载(没有损坏的图像)。如果你需要这个,这里有一些更高级的代码:

Promise.all(Array.from(document.images).map(img => {
    if (img.complete)
        return Promise.resolve(img.naturalHeight !== 0);
    return new Promise(resolve => {
        img.addEventListener('load', () => resolve(true));
        img.addEventListener('error', () => resolve(false));
    });
})).then(results => {
    if (results.every(res => res))
        console.log('all images loaded successfully');
    else
        console.log('some images failed to load, all finished loading');
});

它一直等到所有图像都加载或加载失败。

如果您想尽早失败,请使用第一个损坏的图像:

Promise.all(Array.from(document.images).map(img => {
    if (img.complete)
        if (img.naturalHeight !== 0)
            return Promise.resolve();
        else
            return Promise.reject(img);
    return new Promise((resolve, reject) => {
        img.addEventListener('load', resolve);
        img.addEventListener('error', () => reject(img));
    });
})).then(() => {
    console.log('all images loaded successfully');
}, badImg => {
    console.log('some image failed to load, others may still be loading');
    console.log('first broken image:', badImg);
});

两个最新的代码块用于naturalHeight检测已加载图像中的损坏图像。此方法通常有效,但也有一些缺点:据说当图像 URL 通过 CSScontent属性设置并且图像是未指定其尺寸的 SVG 时,它不起作用。如果是这种情况,您将不得不重构代码,以便在图像开始加载之前设置事件处理程序。这可以通过在 HTML 中指定onloadonerror右键或通过img在 JavaScript 中创建元素来完成。另一种方法是在 HTML 中设置srcdata-srcimg.src = img.dataset.src附加处理程序后执行。

于 2020-03-31T11:49:17.177 回答
17

Promise Pattern 将以最好的方式解决这个问题,我参考了 when.js 一个开源库来解决所有图像加载的问题

function loadImage (src) {
    var deferred = when.defer(),
        img = document.createElement('img');
    img.onload = function () { 
        deferred.resolve(img); 
    };
    img.onerror = function () { 
        deferred.reject(new Error('Image not found: ' + src));
    };
    img.src = src;

    // Return only the promise, so that the caller cannot
    // resolve, reject, or otherwise muck with the original deferred.
    return deferred.promise;
}

function loadImages(srcs) {
    // srcs = array of image src urls

    // Array to hold deferred for each image being loaded
    var deferreds = [];

    // Call loadImage for each src, and push the returned deferred
    // onto the deferreds array
    for(var i = 0, len = srcs.length; i < len; i++) {
        deferreds.push(loadImage(srcs[i]));

        // NOTE: We could push only the promise, but since this array never
        // leaves the loadImages function, it's ok to push the whole
        // deferred.  No one can gain access to them.
        // However, if this array were exposed (e.g. via return value),
        // it would be better to push only the promise.
    }

    // Return a new promise that will resolve only when all the
    // promises in deferreds have resolved.
    // NOTE: when.all returns only a promise, not a deferred, so
    // this is safe to expose to the caller.
    return when.all(deferreds);
}

loadImages(imageSrcArray).then(
    function gotEm(imageArray) {
        doFancyStuffWithImages(imageArray);
        return imageArray.length;
    },
    function doh(err) {
        handleError(err);
    }
).then(
    function shout (count) {
        // This will happen after gotEm() and count is the value
        // returned by gotEm()
        alert('see my new ' + count + ' images?');
    }
);
于 2012-06-17T15:33:40.793 回答
3

Usingwindow.onload将不起作用,因为它会在页面加载后触发,但是图像不包含在此加载定义中。

对此的一般解决方案是ImagesLoaded jQuery 插件。

如果您根本不想使用 jQuery,您至少可以尝试将这个插件转换为纯 Javascript。在 93 行重要的代码和良好的注释下,这应该不是一项艰巨的任务。

于 2012-06-17T12:36:54.530 回答
1

您可以在图像上设置 onload 事件,该事件可以回调执行处理的函数...关于如何处理所有图像是否已加载,我不确定以下任何机制是否有效:

有一个函数可以计算调用 onload 的图像数量,如果这等于页面上的图像总数,则进行必要的处理。

于 2012-06-17T12:45:41.177 回答
1
 <title>Pre Loading...</title>
 </head>

 <style type="text/css" media="screen"> html, body{ margin:0;
 padding:0; overflow:auto; }
 #loading{ position:fixed; width:100%; height:100%; position:absolute; z-index:1; ackground:white url(loader.gif) no-repeat center; }**
 </style>

 <script> function loaded(){
 document.getElementById("loading").style.visibility = "hidden"; }
 </script>

 <body onload="loaded();"> <div id="loading"></div>

 <img id="img" src="avatar8.jpg" title="AVATAR" alt="Picture of Avatar
 movie" />


 </body>
于 2012-06-17T13:08:57.607 回答
-1

我正要建议 Baz1nga 所说的同样的事情。

此外,另一种可能不那么简单但更易于维护的选项是选择最重要/最大的图像并仅将 onload 事件附加到该图像。这里的好处是,如果您以后向页面添加更多图像,则需要更改的代码更少。

于 2012-06-17T12:51:53.273 回答
-3

这很好用:

$(function() {
 $(window).bind("load", function() {
    // code here
 });
});
于 2019-06-12T12:58:31.500 回答