jQuery preload images for iPhone

566 views Asked by At
            // After a page turn
            after: function(opts) {

                var currPageIndex = opts.curr - 1;

                generatePage(currPageIndex);            // This page
                generatePage(currPageIndex + 1);        // Right side page
                generatePage(currPageIndex + 2);
                generatePage(currPageIndex + 3);
            } 
        });
    });

    // Generates the page
    function generatePage(pageID){               

        // Check not already loaded
        if(pageID >= 0 && pageID < arrPages.length && !arrPages[pageID][2])
        {
            arrPages[pageID][2] = true;
            $('#page' + pageID).html('<img src="<%=strProjectPath%>/pages/originals/' + arrPages[pageID][1] + '" alt="Page image" />');
        }
    }

    // Load first page
    $(document).ready(function() {
        generatePage(0);
        generatePage(1);
        generatePage(2);
    });

As you can see, when the document is ready, page 0, 1 and 2 are generated. 0 is the immediately viewable image, then 1 and 2 are preloaded for when they turn the page.

When they turn the page, it loads the current two pages they are viewing (incase the skipped there directly and they aren't preloaded) and the next 2 pages.

How can you bias the loading, so it loads the immediately viewable pages first? Can you use Jquery onload to queue the next pages? At the moment 4 pages could theoretically all load their images simultaneously which would be slow on mobiles.

1

There are 1 answers

0
Attila O. On BEST ANSWER

Sure, you can use the jQuery load(), but then you shouldn't add all the images immediately. You could, for example, queue them up like this:

var preload = function (pageID, rest) {
    $('#page' + pageID).append(
        $('<img/>', {
            src: "<%=strProjectPath%>/pages/originals/' + arrPages[pageID][1] + '"
        }).load(function () {
            rest.length && preload(rest[0], rest.splice(1));
        })
    );
};