Javascript new Image(),如何知道图像是否 100% 加载?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/3511200/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
new Image(), how to know if image 100% loaded or not?
提问by Kirzilla
I'm creating new image using
我正在使用创建新图像
img = new Image();
img.src = image_url;
Then I'm assigning img.src to the img tag's src in DOM
然后我将 img.src 分配给 DOM 中 img 标签的 src
$("#my_img").attr("src", img.src);
How can I know that img.src has 100% loaded? What is the best practice?
img.completeseem to me little buggy in some browsers.
我怎么知道 img.src 已 100% 加载?最佳做法是什么?
img.complete在我看来,某些浏览器中的小错误。
So, in another words, I need to assign img.srcto $("#my_img")only after imgit was 100% loaded.
所以,换句话说,我只需要在 100% 加载后分配img.src给。$("#my_img")img
Thank you!
谢谢!
回答by Sarfraz
Use the loadevent:
使用load事件:
img = new Image();
img.onload = function(){
  // image  has been loaded
};
img.src = image_url;
Also have a look at:
也看看:
回答by Watchmaker
Using the Promise pattern:
使用承诺模式:
function getImage(url){
        return new Promise(function(resolve, reject){
            var img = new Image()
            img.onload = function(){
                resolve(url)
            }
            img.onerror = function(){
                reject(url)
            }
            img.src = url
        })
    }
And when calling the function we can handle its response or error quite neatly.
当调用函数时,我们可以非常巧妙地处理它的响应或错误。
getImage('imgUrl').then(function(successUrl){
    //do stufff
}).catch(function(errorUrl){
    //do stuff
})

