我想知道图像何时完成加载.有没有办法用回调来做到这一点?
如果没有,有没有办法做到这一点?
.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/
Image.onload()通常会起作用.
要使用它,您需要确保在设置src属性之前绑定事件处理程序.
相关链接:
Image.onload()上的Mozilla
用法示例:
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);
};
您可以使用Javascript图像类的.complete属性.
我有一个应用程序,我将一些Image对象存储在一个数组中,它将动态添加到屏幕上,当它们加载时,我将更新写入页面上的另一个div.这是一段代码片段:
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); }
您可以在jQuery中使用load() - 事件,但如果从浏览器缓存加载图像,则不会总是触发.这个插件https://github.com/peol/jquery.imgloaded/raw/master/ahpi.imgload.js可以用来解决这个问题.
生活对于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')
});