Check if image is loaded or not using jQuery

← PrevNext →

People often ask me this. I have recently made some changes in this tool and have implemented the same. So, let me show you how to check if an image has successfully loaded on a web page or not using jQuery.

jQuery has many built-in methods that are easy to use. Of course, you’ll have be little careful with the versions that you use.

Note: I have come across few solutions on the internet where they simply share a jQuery code, however they fail to mention which version of jQuery you must embed in your application to use a particular method.

Now, lets see some examples.

<!DOCTYPE html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
</head>
<body>
  <p>
    <img src='../../images/about-arunbanik.jpg' id='img'>    
    <!--  make some changes to image name and then check again. -->
  </p>
</body>

<script>
    $('#img').load(function () {
        alert('image has loaded');
    })
    .error(function () {
        alert('failed to load the image');
    });
</script>
</html>
Try it

Here, I am using .load() method to check if the image (inside the <body> tag) has successfully loaded or not. Along with the .load() method, I am also using the .error() method. So if there is an error, the script will know and accordingly show a message.

Now, see at the jQuery version (the CDN) I am using (in the above code) inside the <head> tag.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

You can also use an older version to execute the above code. For example,

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

Why am I specifically mentioning the versions here? Its because the way the methods load and error are used in the above example, using older versions of jQuery

So, if you are using a newer version, the use of methods is slightly different.

Using higher jQuery version

Remember, if you are using a higher version, then the methods to check if image is loaded, will change.

For example, if the version you are using is this… (or even higher version)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

then you must use the .on() method.

<!DOCTYPE html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
  <p>
    <img src='../../images/about-arunbanik.jpg' id='img'>    
  </p>
</body>

<script>
    $('#img').on("load", function () {
        alert('image has loaded');
    })
    .on("error", function () {
        alert('failed to load the image');
    });
</script>
</html>
Try it
Conclusion

Hope it helps. Remember, when you are using a framework, always check for the latest version and the method and properties that come with it. Also learn how to use the methods.

← PreviousNext →