Javascript - execute after all images have loaded

前端 未结 9 1344
陌清茗
陌清茗 2020-12-01 05:53

Having read other people\'s questions I thought

window.onload=...

would answer my question. I have tried this but it executes the code the

9条回答
  •  既然无缘
    2020-12-01 06:20

    Promise Pattern will solve this problem in a best possible manner i have reffered to when.js a open source library to solve the problem of all image loading

    function loadImage (src) {
        var deferred = when.defer(),
            img = document.createElement('img');
        img.onload = function () { 
            deferred.resolve(img); 
        };
        img.onerror = function () { 
            deferred.reject(new Error('Image not found: ' + src));
        };
        img.src = src;
    
        // Return only the promise, so that the caller cannot
        // resolve, reject, or otherwise muck with the original deferred.
        return deferred.promise;
    }
    
    function loadImages(srcs) {
        // srcs = array of image src urls
    
        // Array to hold deferred for each image being loaded
        var deferreds = [];
    
        // Call loadImage for each src, and push the returned deferred
        // onto the deferreds array
        for(var i = 0, len = srcs.length; i < len; i++) {
            deferreds.push(loadImage(srcs[i]));
    
            // NOTE: We could push only the promise, but since this array never
            // leaves the loadImages function, it's ok to push the whole
            // deferred.  No one can gain access to them.
            // However, if this array were exposed (e.g. via return value),
            // it would be better to push only the promise.
        }
    
        // Return a new promise that will resolve only when all the
        // promises in deferreds have resolved.
        // NOTE: when.all returns only a promise, not a deferred, so
        // this is safe to expose to the caller.
        return when.all(deferreds);
    }
    
    loadImages(imageSrcArray).then(
        function gotEm(imageArray) {
            doFancyStuffWithImages(imageArray);
            return imageArray.length;
        },
        function doh(err) {
            handleError(err);
        }
    ).then(
        function shout (count) {
            // This will happen after gotEm() and count is the value
            // returned by gotEm()
            alert('see my new ' + count + ' images?');
        }
    );
    

提交回复
热议问题