I'm coding a website that displays picture albums, the page is loading the thumbs and applies white overlays on each picture before they are fully loaded.
I coded this in local and it works fine. But uploading the files on my server and loading the page brings few errors of display, some white overlay are not fading out because the jQuery load function is not triggered since images load before the script is loaded and being applied.
The solution would be to apply white overlay only on images that are still loaded when the jQuery script is being executed.
My question is how to know if a specific element in the page is still being fetched or has completely been rendered on the screen ?
NOTE : here's the page http://www.benjamindegenne.com/portfolio/numeric/upper-playground/
To determine whether an image has been completely loaded, you can use the HTMLImageElement interface's complete attribute. It returns true if the image has completely loaded and false otherwise. We can use this with naturalWidth or naturalHeight properties, which would return 0 when the image failed to load.
The <img /> element has the onLoad event that allows us to detect when the image is loaded, and also the onError event that tells us if an error happens when trying to retrieve the image.
The previous solution was incorrect. (Thanks to @donut).
Here is alternative simple way to do this using jQuery -
$(function() {
$("<img src='img_01.jpg' />").load(function() {
// Image img_01.jpg has been loaded
});
});
JavaScript
Use Image pre-loading in JavaScript -
img1 = new Image();
img1.src = "image.jpg";
// at this line image.jpg has been loaded
After img1.src = "image.jpg";
, you can assure that image has been loaded and you can write your business logic
jQuery
Here is a simple jQuery plugin to accomplish this -
// image preloading plugin
$.fn.preload = function () {
this.each(function () {
$('<img/>')[0].src = this;
// at this line "this" image has been loaded
});
};
Sample usage -
var imagesToPreload = ["img01.jpg", "img02.jpg", "img03.jpg"];
imagesToPreload .preload();
// at this line all images has been loaded
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With