Skip to content Skip to sidebar Skip to footer

Order Issue With Append In A File Reader

I got a Jquery function that read a FilesList and display in an IMG html object the image. function load_images(files) { for (var i = 0; i < files.length; i++) { //

Solution 1:

The method readAsDataURL is asynchronous meaning that your loop will create a lot of requests to load data, but because the method is asynchronous there is not way to to know in which order the onload callback will be called. The behaviour is non-deterministic.

This could be solved by storing all the elements in an array along with their index and then actually rendering out all the images when they have all loaded completely.

Another alternative is creating a placeholder div when the requests is started and capture it in the closure of the onload callback. Then you could append the image to that div, this would cause the behaviour you want.

Like this:

functionload_images(files) {
    for (var i = 0; i < files.length; i++) {
        // Validate the image typeif(validate_file(files[i])) {
            var reader = newFileReader(),
                div    = $("<div></div>");
            $(".upload_thumbnails").append(div);            

            reader.onload = function(e) {    
                div.append(render_thumb(e.target.result, i)); // Return a string with the img object
            };
        } 
        reader.readAsDataURL(f);
    } 
}

Post a Comment for "Order Issue With Append In A File Reader"