Fast loading of many images in html

I encode a script in which the user selects a data range, and then I get a bunch of images (over 150) from the server, and then I loop through them to make something like a movie. What I want to know is the most efficient download method, preventing delay when moving through images.

I am currently receiving images from the server using Ajax and storing them in an array of Image objects in JavaScript. In HTML, I have a div tag in which I want to put images. After I finish creating the entire Image object (and set their own src) in the array, I do the following:

imgElem = document.createElement('img'); document.getElementById('loopLocation').appendChild(imgElem); imgElem.src = images[0].src; 

After that, I just make this last call, but change the loop index. I do this every 400 ms. The loop works, but sometimes it lags, and it freezes in the image longer than it should be. I want to know if I can improve this on the client side or if I need a server that responds faster.

+4
javascript html ajax
Apr 01 2018-12-12T00:
source share
2 answers

You may consider spriting , which puts all images in one large image. with this, you just need to upload one large image, and then just move for each scene.

or you can also preload these 150 images before using them. you can use a JS array to store Image objects and then skip that array to get your images.

 var images = []; var expectLoaded = 150; for(var i = 0; i<expectLoaded;i++){ (function(i){ //new image object var img = new Image(); //onload hander img.onload = function(){ //after load, push it into the array images.push[img]; //and check if the all has loaded if(images.length === expectLoaded){ //preload done } } //start loading this image img.src = //path to image[i]; },(i)); } 



Cycles

block user interface thread. JS is single-threaded, that is, the code is executed in a linear fashion, one after the other. everything that comes after this loop statement will wait for the loop to end. if this loop takes a long time ... take some coffee. plus, since you are manipulating the DOM, you do not see the changes because the user interface thread is blocked.

but there are ways around this, and one of them uses timeouts to delay and queue the code for later execution when JS is not busy.

 function animate(frameNo){ //animate frame[frameNo]; if(frameNo < total_frames){ //make the UI breate in between frames setTimeout(function(){ //so that changes reflect on the screen animate(++frameNo); //then animate next frame },200); } } //start animate(0); 
+6
Apr 01 '12 at 7:10
source share

I agree with Joseph in his second paragraph. Here's a good link to preload the image before starting the loop: http://www.javascriptkit.com/javatutors/preloadimagesplus.shtml

+2
Apr 01 '12 at 7:16
source share



All Articles