jQuery: Preload images

If your web page uses a lot of images that aren’t visible initially (e.g., on hover) it makes sense to preload them.

A typical image tag is <img src=”photo.jpg”>.

<!DOCTYPE html>
<html>
    <head>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
        <title>Preload Images</title>      
        <script>
            $(function () {
                $.preloadImages = function () {
                    for (var i = 0; i < arguments.length; i++) {
                        $('img').attr('src', arguments[i]);
                    }
                };

                $.preloadImages('http://i1.wp.com/www.trrvel.com/wp-content/uploads/2015/12/image-2.jpeg', 'http://i1.wp.com/www.trrvel.com/wp-content/uploads/2015/12/image-1.jpeg');
                alert('images loaded');
            })
        </script>
    </head>
    <body>
        <p>Preload images</p>
    </body>
</html>

button

Leave a comment

Leave a Reply