Search code examples
mootoolsdelay

Non-timeout method of waiting for an image to load before proceeding?


I have an Fx.Slide instance that loads content via ajax and then slides open the element. It correctly waits for the AJAX call to return (and populate its target element's content) before sliding open, but because I am not transferring image data, only the url, the image is still being downloaded by the user's browser when the Fx.Slide instance is toggled.

Hence, when the element is measured, it does not take the image's size into account does not slide open far enough.

A .delay() would work, but it's a hack-ish workaround.

Relevant jsFiddle


Solution

Thanks to lorenzo-s, the following solution works superbly:

var container = document.id('something');
new Request({
    url: '/path/to/listener',
    onSuccess: function(imageUrl) {
        Asset.image(imgSrc, {
            title: 'Something',
            onLoad: function() {
                // .. trigger the Fx.Slide instance here
            }
        }).inject(container);
    }
});

Solution

  • You should use Asset.image() method from Mootools More.

    That method preloads an image and returns the img element. You can use the onLoad property (on the second argument object) that will be called once the image is "ready".

    Asset.image('http://url.to/your/image.jpg', {
        onLoad: function() {
            alert('Image ready.');
        }
    });
    

    Updated example here: http://jsfiddle.net/6Lpeu/3/