The image's load
event is almost certainly firing before you hook the event. Since it's already fired when you hook the event, you never see it occur.
Also, you start out hiding the image (#imgload
), but you never then show it.
To ensure that you get the event, you have to hook load
before setting the image's src
.
Alternately, you can use the image's complete
property to know if it's already been loaded:
// show loading image
$("#loader_img").show();
$("#imgload").hide();
// main image loaded ?
var img = $("#imgload");
if (img[0].complete) {
imageDone();
} else {
img.on('load', imageDone);
}
function imageDone() {
// hide/remove the loading image
$("#loader_img").hide();
// And show the image!
img.show();
}
You also have to ensure that the code above runs after the elements have been created. The best way to do that is to put your script
tag containing the code after the elements it refers to in the HTML (usually putting it just before the closing </body>
tag works well). As a second-best solution, you can use jQuery's ready
function. Either way, you'll still need to handle the possibility the load
event has already fired.
Here's an example:
<div id="loader_img">Loading</div>
<div class="content">
<img id="imgload" src="https://i.stack.imgur.com/rTQCa.jpg?s=512&g=1" />
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
(function() { // Avoid creating globals
// show loading image
$("#loader_img").show();
$("#imgload").hide();
// main image loaded ?
var img = $("#imgload");
if (img[0].complete) {
console.log("Complete");
imageDone();
} else {
console.log("Wait for load");
img.on('load', imageDone);
}
function imageDone() {
console.log("Loaded");
// hide/remove the loading image
$("#loader_img").fadeOut();
// And show the image!
img.show();
}
})();
</script>