Alex
Alex

Reputation: 38509

Loading / inserting images after page has loaded / scrolled

I'm trying to load images onto the page after it has loaded.

The best (but crude) way to demonstrate this is:

<div id="images">
    <script type="text/javascript">
        for (var i = 0; i < 10000; i++) {
            document.write("<img src=\"imgs/"+i+".jpg\" \">");
        }
    </script>
</div>

jsFiddle: http://jsfiddle.net/alexjamesbrown/XPBdg/

... Yes, loading 10000 tags onto the page!

What I'd like to happen is the page load, then the 'for' loop fires after the page has loaded, one after the other (as not to disrupt the browser too much)

I also tried this in jQuery, but it literally hung the browser...

$(function(){
    for (var i = 0; i < 10000; i++) {
        $('#images').append('<img src=\"img/'+i+'.jpg\" width: 20px; height: 20px;\ class=\"img\">')
    }
})

So, a bit like a simple version of the 'infinate scroll' type apps: http://www.innovativephp.com/demo/infinitescroll/

using a for loop, instead of retrieving data from the server....

Upvotes: 0

Views: 296

Answers (2)

Bruno
Bruno

Reputation: 5822

To load each image one at a time try

var imageCount = 0;

function nextImage( ) {
    var img = new Image(); // create image element
    img.src = "http://lorempixel.com/40/40" + imageCount; // use imageCount to change image
    img.onload = function( ) { 

        if( imageCount <= 10000 ) {

            imageCount++;
            var imgElement = document.getElementById("images");
            imgElement.appendChild( img );
            nextImage(); // only once image has loaded should we try to load another
        }
    }
}

nextImage();​

Just got it working. Have a look at the fiddle here

By the way you could delay loading further by using something like

setTimeout( nextImage, 100 );

Upvotes: 1

edigu
edigu

Reputation: 10089

Loading 10.000 img elements in a single request wont be a good practice. You would think about to change the logic.

Anyway, you can try something like following to increase performance.

<div>
        <script type="text/javascript">
            var elems = [], limit = 5000;
            while(limit--) {
                elems.push('<img src="http://lorempixel.com/40/40" />');
            }
            document.write( elems.join(' ') );
            // or using jquery : $('body').append( elems.join(' ') );
        </script>
</div>​​​​​​​​

Touching to DOM in every single loop iteration greatly decreases the performance.

Upvotes: 0

Related Questions