Jquery .one() Load And Error Events Not Working
functiononImagesLoaded($container, callback) {
var $images = $container.find("img");
var imgCount = $images.length;
if (!imgCount) {
callback();
} else {
$("img", $container).each(function () {
$(this).one("load error", function () {
imgCount--;
if (imgCount == 0) {
callback();
}
});
if (this.complete) $(this).load();
});
}
}
And how to use it...
onImagesLoaded($("#compare-table-scrollable"), function() {
alert("images loaded");
});
Notice the addition of if (this.complete)
, which allows the function to count images that are cached and therefore load before the function is called.
Solution 2:
You're not hooking the events until very late in the page load process, after the events have already fired. Note the second drop-down box on the upper left side of jsFiddle, which says "onload". This is jsFiddle's extremely surprising default, which is to wrap your JavaScript code in a window
load
event handler. That handler doesn't get fired until all the images have loaded or failed to load.
If you change that drop-down to no wrap - <body>
, you get the alert: http://jsfiddle.net/X4AmG/3/
That said, with the images being specified in the markup, I'd be worried about a load
or error
event managing to get fired before your code hooked up its handlers. For that reason, I'd probably do something like this instead:
// Get the imagesvar imgs = $('#compare-table-scrollable img');
// Schedule the first check for DOM ready
$(checkForImagesDone);
// Our check functionfunctioncheckForImagesDone()
{
var counter = 0;
imgs.each(function()
{
if (this.complete)
{
++counter;
}
});
if (counter === imgs.length)
{
alert("All complete");
}
else
{
setTimeout(checkForImagesDone, 50); // 50ms
}
}
Post a Comment for "Jquery .one() Load And Error Events Not Working"