0

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:

  1. Load the images and append them to the DOM into an invisible preloadContainer.

  2. If loading is successful, load a callback-function which checks, whether or not all images have been preloaded ("noOfPreloadedImages++; if(noOfPreloadedImages == noOfImagesToLoad)...").

  3. 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...?

Sven S
  • 103
  • 1
  • 1
  • 7

3 Answers3

0

It doesn't mean it can't be done, but I've actually never seen an error handler attached to a DOM object.

How about doing a $.ajax() in the onload event for the page? Then you can attach the right callbacks to the respective events.

Vidya
  • 29,932
  • 7
  • 42
  • 70
0

Your code is always triggering the success/error handlers as you're calling them when setting up the event handling:

test.on('error', errorHandler());
test.on('load', successHandler());

You're actually attaching the result of the function calls to the handlers rather than the functions themselves.

What you want is this instead:

test.on('error', errorHandler);
test.on('load', successHandler);
dmuir
  • 283
  • 4
  • 8
-1

I wrote an image preloader module that works perfectly. It uses plain old JavaScript, which means you can start preloading your images before jQuery has loaded. It also triggers callbacks and will wait for jQuery to load before firing your callback if you want it to. Check it out and let me know if you end up using it: http://test.neilgirardi.com/

The above URL contains a demo which preloads 3.1MB worth of images and triggers a jQuery .cycle() slideshow as a callback.

Neil Girardi
  • 4,533
  • 1
  • 28
  • 45
  • Thank you for the link, you have written a great script! Would love to be at a point where I could write Javascript-without-jQuery, still have a lot to learn. Anyway, I ended up using my "solution" under "[EDIT]", even though I do not really understand why it works. – Sven S Oct 23 '13 at 00:41
  • Nice work Sven. You did it exactly the right way. The key is to create the DOM element, bind the callbacks and THEN set the source. It has to be done in that order. – Neil Girardi Oct 23 '13 at 01:25
  • Link does not load – AllisonC Jan 25 '18 at 13:59