I was wondering if it were possible to check if all the images within a div are loaded before running executing?
HTML:
<body onload="check()">
<div id="testdiv">
<img id="test" src="assets/image.jpg" />
</div>
</body>
Javascript:
function check() {
var test = document.getElementById("testdiv")plete;
alert(test);
}
It returns "undefined".
I was wondering if it were possible to check if all the images within a div are loaded before running executing?
HTML:
<body onload="check()">
<div id="testdiv">
<img id="test" src="assets/image.jpg" />
</div>
</body>
Javascript:
function check() {
var test = document.getElementById("testdiv").plete;
alert(test);
}
It returns "undefined".
Share Improve this question asked Feb 21, 2014 at 17:37 user3256987user3256987 841 silver badge9 bronze badges 8- .plete is used for ajax calls not for the image loading as far as i know – Kawinesh S K Commented Feb 21, 2014 at 17:39
- By "executing" do you mean "before running script"? – royhowie Commented Feb 21, 2014 at 17:40
-
1
you can use the
onload
onimg
tag that image is loaded or not. – Suman Bogati Commented Feb 21, 2014 at 17:40 - @KawineshSK - w3schools./jsref/prop_img_plete.asp it is for image pletetion. – user3256987 Commented Feb 21, 2014 at 17:43
-
@SumanBogati - I am aware of that, but the div will have over 100 images in it, I want to have it say
images are loading...
then once all loaded to change to displaying the images, for this I need to check every single one separately OR check if the div is "loaded" – user3256987 Commented Feb 21, 2014 at 17:45
5 Answers
Reset to default 1If you want to check whether all the images has been loaded properly, you can wrap your code inside $(window).load(function() {....});
$(window).load(function() {
alert('test');
});
or you can also try this:
var $images = $('div#testdiv img');
var loaded_images_total = 0;
$images.load(function(){
loaded_images_total ++;
if (loaded_images_total == $images.length) {
alert('test');
}
});
How about this,
<script type="text/javascript">
function check(d) {
alert(d.id+":: Loaded" );
}
</script>
<img id="test" src="assets/image.jpg" onload="check(this)"/>
You can use the load event.
» Fiddle sample «
$(document).ready(function(){
$("#test").load(function(e) {
console.log("OK", e);
})
.error(function(e) {
console.log("ERROR", e);
});
})
Where we attach, as by example from OP, to load
on <img>
tag.
<div id="testdiv">
<img id="test" src="http://lorempixel./output/fashion-q-c-300-200-2.jpg" />
</div>
Here's an ES6 function, awaitImgs()
, that you can use to perform a task after all <img>
elements in the specified container element have resolved (i.e., have loaded or failed to load).
Basic usage:
awaitImgs(someContainerElement).then(plete).catch(failed);
Comments wele.
<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 plete. If an given image isn't
// already plete, wait for its onload or onerror events to be dispatched.
imgs.forEach((img) => {
console.log(`src: ${img.getAttribute('src')}, plete: ${img.plete}, 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.plete) {
// This image has finished loading
if (img.naturalWidth > 0) {
// We treat plete images with greater-than-zero width as valid and resolved
handleImgLoaded(img);
} else {
// We treat plete 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 plete = (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(plete).catch(failed);
</script>
</body>
</html>
$(window).load(function(){
// everything on the page has loaded.
});
That will fire once things load. However, it won't tell you if a particular div has loaded all of its assets, nor will it tell you if you have broken images.
If you want to do a check for a particular div, this is harder. You can't really check to see if images are loaded after HTML parse, because the HTML engine can load them before you script gets a chance to add a listener. So, you need to add listeners directly to each image as it gets added, which means you've got to be the one to do it.
There isn't a 'sugar' way of doing this, which leaves you with something like this:
<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 pleted. 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>