Lab Lab Lab Lab -4 years ago 98
Javascript Question

How to escape double image loading?

In my web project, I have a different html pages and the _Layout page.
This layout page displays the profile photo of a user like this:

<img src="~/Path/avatar.png" id="avatar">


And I implemented one thing: if the user haven't ever uploaded the profile photo, _Layout page will always display the standard
avatar.png
. Else, if he uploaded their avatar, I do next:

$.ajax({
type: 'POST',
url: '/Account/HasAvatar/',
success:
function (data) { //data - it's the name of the image file
console.log(data);
if (data == null)
return;
$("#avatar").attr("src", window.location.protocol+"//"+window.location.host+"/Path/" + data);
}
})


If the current user has already uploaded the profile photo, controller method
HasAvatar()
returns its name and then jquery changes the standard
<img src="">
to an already existed image. But here I have a problem. When a user load any page, firstly he can see the standard avatar and only then (in 0.2 sec) the current user's image is loaded. How to escape this double image loading? Any ideas?

Answer Source

You can use css to hide the img initially e.g. using style="display:none;" and then when the image loads, display it again like this:

$.ajax({
    type: 'POST',
    url: '/Account/HasAvatar/',
    success:
        function (data) { //data - it's the name of the image file
            console.log(data);
            if (data == null){
                $("#avatar").css('display', 'initial');
                return;
            }
            $("#avatar").one('load', function(){
                $("#avatar").css('display', 'initial');
            });
            $("#avatar").attr("src", window.location.protocol+"//"+window.location.host+"/Path/" + data);
        }
})
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download