R
R
Ruslan2013-06-01 20:04:55
JavaScript
Ruslan, 2013-06-01 20:04:55

Tracking the progress of image caching?

Hello!
There is the following javascript code:

function preloadImages(array) {
        if (!preloadImages.list) {
            preloadImages.list = [];
        }
        for (var i = 0; i < array.length; i++) {
            var img = new Image();
            img.src = path+array[i];
            preloadImages.list.push(img);
        }
    }

The above code creates an array of images based on an array of image paths. This is how images are cached in the page object model. Next, you can quickly iterate over the src attribute of the image element on the page, substituting the path from the primary array, thereby creating an animation effect.
Question: how to track at a certain point in time how many images have already been loaded by the browser. in general, you need to display the progress bar of loading images into the cache.
Thanks for the advice.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
V
vitvad, 2013-06-01
@Razbezhkin

Not a very authoritative source, but here is image.complete The
Image object has a complete flag, if the image is already loaded and will be taken from the cache, the flag is set to true.

var img =  new Image();
img.onload = function(){
  count++;   
}
if(image.complete){
  count++;
}

if(count == imageArray.length) doSomething();

M
Malyw, 2013-06-01
@Malyw

During the loading of an image, there are three options for subsequent events with it:
1) The image will be loaded (the load event will
fire
) abort event)
You can use the following code:

var img = new Image();
img.onload = function(){
 console.log('img is loaded!');
}
img.onerror = function(){
 console.log('there is some error, when trying to load img');
}
img.onabort = function(){
 console.log('img loading is aborted');
}
img.src = 'https://www.google.com/images/srpr/logo4w.png';

Event listeners can also be hung via addEventListener.

M
Malyw, 2013-06-01
@Malyw

That is, when any of the above events fires, you increment some variable (for example, “processed”), and update the percentage of images “processed” by the browser like this:

updateLoderView( processed/ preloadImages.list.length);

Or perform some other actions when the “load”, “error” events are triggered - this is already at your discretion.

R
Ruslan, 2013-06-01
@Razbezhkin

Thank you!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question