我想知道在运行执行之前是否可以检查div中的所有图像是否都已加载?
HTML:
<body onload="check()">
<div id="testdiv">
<img id="test" src="assets/image.jpg" />
</div>
</body>
使用Javascript:
function check() {
var test = document.getElementById("testdiv").complete;
alert(test);
}
返回“undefined”。
答案 0 :(得分:1)
如果要检查是否已正确加载所有图像,可以将代码包装在$(window).load(function() {....});
$(window).load(function() {
alert('test');
});
或者你也可以试试这个:
var $images = $('div#testdiv img');
var loaded_images_total = 0;
$images.load(function(){
loaded_images_total ++;
if (loaded_images_total == $images.length) {
alert('test');
}
});
答案 1 :(得分:1)
您可以使用加载事件。
$(document).ready(function(){
$("#test").load(function(e) {
console.log("OK", e);
})
.error(function(e) {
console.log("ERROR", e);
});
})
我们附加的地方,例如来自OP的示例,附加到load
标记上的<img>
。
<div id="testdiv">
<img id="test" src="http://lorempixel.com/output/fashion-q-c-300-200-2.jpg" />
</div>
答案 2 :(得分:1)
这个怎么样,
<script type="text/javascript">
function check(d) {
alert(d.id+":: Loaded" );
}
</script>
<img id="test" src="assets/image.jpg" onload="check(this)"/>
答案 3 :(得分:0)
$(window).load(function(){
// everything on the page has loaded.
});
一旦事情加载就会解雇。但是,它不会告诉您特定div是否已加载其所有资产,也不会告诉您是否已损坏图像。
如果你想检查一个特定的div,这就更难了。您无法真正检查HTML解析后是否加载图像,因为HTML引擎可以在脚本有机会添加侦听器之前加载它们。因此,您需要在添加时直接向每个图像添加侦听器,这意味着您必须成为执行此操作的人。
没有'糖'的方式这样做,这让你有这样的事情:
<div id="dynamic"></div>
<script>
// load directly in the page. Not necessary, but simpler to talk about.
var imageCounter=0, images = ['foo/bar.jpg','foo/bar2.jpg', .... ];
function checkCounter(){
imageCounter++;
if (imageCounter >=images.length)
{
// load completed. Do some stuff.
}
};
for (var ii=0; ii< images.length; ii++)
{
var pImg = $('<img>')
.on('load',function(){imageCounter++; checkCounter();})
.on('error', function(){imageCounter++;checkCounter();});
pImg.attr('src', images[ii]);
pImg.appendTo('#dynamic');
}
</script>
答案 4 :(得分:0)
这是ES6函数awaitImgs()
,在指定容器元素中的所有<img>
元素都已解析(即加载或加载失败)之后,您可以使用它来执行任务。
基本用法:
awaitImgs(someContainerElement).then(complete).catch(failed);
欢迎评论
<html>
<head><title>Image Load Test</title></head>
<body>
<div id="content">
<img src=""/>
<img src="some_image.png"/>
<img src="some_other_image.jpg"/>
</div>
<script type="text/javascript">
/**
* Returns a promise that is fulfilled when ALL <img> elements in the specified container element
* have either loaded, failed to load, or never attempted to load due to an empty or missing src
* attribute.
*/
let awaitImgs = (elem) => {
console.log('=================BEGIN WAITING FOR IMGS===============');
return new Promise((resolve) => {
let imgs = Array.from(elem.querySelectorAll('img'));
let numImgs = imgs.length;
let numImgsResolved = 0;
let numImgsFailed = 0;
let handleImgLoaded = (img) => {
console.log('Complete: ' + img.src);
numImgsResolved++;
checkForDone();
};
let handleImgFailed = (img) => {
console.log('Failed: ' + img.src);
numImgsResolved++;
numImgsFailed++;
checkForDone();
};
let checkForDone = () => {
if (numImgsResolved === numImgs) {
// All images have either loaded or failed, so fulfil the Promise
resolve(numImgsFailed);
}
};
console.log(`Waiting for ${imgs.length} images...`);
// Examine each image to determine whether it is already complete. If an given image isn't
// already complete, wait for its onload or onerror events to be dispatched.
imgs.forEach((img) => {
console.log(`src: ${img.getAttribute('src')}, complete: ${img.complete}, naturalWidth: ${img.naturalWidth}`);
let imgIsEmpty = !img.hasAttribute('src') || img.getAttribute('src') === '';
if (imgIsEmpty) {
// This img element has no src attribute OR src is set to the empty string. This is an
// edge case that should be avoided. We treat such img elements as resolved.
handleImgLoaded(img);
} else if (img.complete) {
// This image has finished loading
if (img.naturalWidth > 0) {
// We treat complete images with greater-than-zero width as valid and resolved
handleImgLoaded(img);
} else {
// We treat complete images with 0 width as invalid, but resolved
handleImgFailed(img);
}
} else {
// This image hasn't finished loading yet, so handle load and
// error cases with event listeners
let loadListener = (e) => {
e.target.removeEventListener('load', loadListener);
handleImgLoaded(e.target);
};
img.addEventListener('load', loadListener);
let errorListener = (e) => {
e.target.removeEventListener('error', errorListener);
handleImgFailed(e.target);
};
img.addEventListener('error', errorListener);
}
});
});
};
// Example usage:
let div = document.querySelector('#content');
let complete = (numFailed) => {
console.log(`All images resolved. Number of images that failed to load: ${numFailed}`);
// Work to perform after all images have loaded goes here
};
let failed = (result) => {
// Safety net that executes if an exception is thrown inside awaitImgs()
console.log(`Error: ${result}`);
};
awaitImgs(div).then(complete).catch(failed);
</script>
</body>
</html>