Search code examples
jqueryajaximageloader

Loader for images that are in another page that are gathered with ajax, in jQuery


Edit: Here is the new code:

        $("#normalcontent").hide("fast").load($this.attr("href") +" #normalcontent","",function(){
        $(this).slideDown("normal");
        $(this).find("img").each(function(){
            if($(this).hasClass("large"))
            {
                var myThis=$(this);
                myThis.css("display","none");
                var img = new Image();
                $(img).attr("src", "images/ajax-loader.gif");
                $(img).css({
                    border:"none",
                    width:"16px",
                    height:"11px"
                });
                myThis.after(img);
                myThis.load(function(){
                    $(img).remove();
                    myThis.fadeIn("normal");
                })
                .error(function(){
                    $(img).attr("src","images/errorIcon.png").css({
                        border:"none",
                        width:"14px",
                        height:"14px"
                    });
                });
            }
        });
    });

Hello.

Let's say I have a link in "index.php", when I click on that link, it loads, via ajax, a content from a page "content.php" into a div element in "index.php", that has an id of "#content". That content in "content.php" has large images. I want to display an image loader, say "ajax-loader.gif", instead of those large images, until the images are downloaded by client.

( I know how to have an image loader .gif for the images on "index.php". )

How can I achieve this?


Solution

  • $('#blah').load('/index.php #content', function () {
        $(this).find('img').each(function () {
            var self = $(this),
                replacee = $('<img src="/ajax-loader.gif/>');
    
            this.onload = function () {
                replacee.replaceWith(self);
            };
    
            self.replaceWith(replacee);
        });
    });
    

    I'd be careful about your layout though... I doubt swopping large images for small loaders is ideal. As a user, I'd prefer to delay the showing of the whole content, until all images have loaded.