I'm building a gallery-slider-script and try to preload the images all in advance before appending them to the gallery.
My design should do the following:
Load the images and append them to the DOM into an invisible preloadContainer.
If loading is successful, load a callback-function which checks, whether or not all images have been preloaded ("noOfPreloadedImages++; if(noOfPreloadedImages == noOfImagesToLoad)...").
If loading failed because the image-resource is not avaible, call an error-callback-function.
Here is a complex, "full" version of my code:
$('<img />')
.attr({'src': galleries[i].slides[j].imageUrl, 'id': 'galleryImg'+j})
.on('load', checkPreloadComplete(i))
.on('error', checkPreloadError(i, j))
.attr({'src': galleries[i].slides[j].imageUrl, 'id': 'galleryImg'+j})
.appendTo(preloadContainers[i])
.wrap('<div id="slide'+j+'" class="slide" />');
Now, the problem is, that the error-callback is always being called. I tried playing with the function-chain, with no success.
So, here is a little test-code which also always throws an error, regardless of whether or not the image-resource is available:
$(function() {
$(document).ready(function() {
$("<img />")
.attr({'src': 'http://www.google.de/images/srpr/logo11w.png'})
.on('error', errorHandler())
.appendTo('body');
});
function errorHandler() {
console.log("Error loading image.");
};
});
Here is a jsFiddle: http://jsfiddle.net/SvenS/FhYQ8/
What am I doing wrong? Where is my thinking wrong?
[EDIT]
Ok, that was weird. Some observations:
This always triggers an error/success:
$(function() {
$(document).ready(function() {
var test = $("<img />").appendTo('body');
test.on('error', errorHandler());
test.on('load', successHandler());
test.attr({'src': 'http://www.google.de/images/srpr/logo11w.png'});
});
function errorHandler() {
console.log("Error loading image!");
};
function successHandler() {
console.log("Image loaded successfully!");
}
});
But here is what works, strangely enough:
$(function() {
$(document).ready(function() {
var test = $("<img />").appendTo('body');
test.on('error', function(e) { errorHandler(); });
test.on('load', function(e) { successHandler(); });
test.attr({'src': 'http://www.google.de/images/srpr/logo11w.png'});
});
function errorHandler() {
console.log("Error loading image!");
};
function successHandler() {
console.log("Image loaded successfully!");
}
});
I really don't understand why, maybe someone with a deeper understanding can help me...?