Thursday, June 18, 2015

Display loader until the image gets fully loaded using javascript

One of the most common problems with web based applications involving high resolution images is the time taken to load the images. The images would load slowly section by section and it might be annoying for end users. To resolve this issue, we can display a loader before the image gets fully loaded and then display the actual image with a simple fade effect through jQuery:

First set the loader image as the default image

<img src="/ajax-loader.gif" id="profileImage" />


Declare the javascript to handle image loading

function loadImage(control, src) {
        var loadImage = new Image();
        loadImage.src = src;
        if (loadImage.complete) {
            control.hide().attr('src', src).fadeIn();
            loadImage.onload = function () { };
        }
        else {
            loadImage .onload = function () {
                control.hide().attr('src', src).fadeIn();
                loadImage.onload = function () { };
            }
        }
}


Call the function

loadImage($('#profileImage'), 'https://www.microsoft.com/global/learning/en-us/PublishingImages/ms-logo-site-share.png');

- Notice that I've used jQuery to fetch image object i.e. $('#profileImage') because of which I could use control.hide() in the function directly without having to use $(control).





No comments: