开发者

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

开发者 https://www.devze.com 2023-04-12 11:58 出处:网络
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'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 jQ开发者_运维技巧uery 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/


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


https://github.com/desandro/imagesloaded - images loaded jQuery plug in will do that for you ;-)

0

精彩评论

暂无评论...
验证码 换一张
取 消