Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to know whether or not a image has been loaded using javascript

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/

like image 878
vdegenne Avatar asked Oct 10 '11 11:10

vdegenne


People also ask

How can you tell if an image is not loaded?

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.

How do you know if all images are loaded react?

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.


1 Answers

Updates

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

like image 167
Ramesh Soni Avatar answered Oct 06 '22 01:10

Ramesh Soni