1

While creating a JQuery plugin that required image dimensions, I discovered that webkit browsers like Chrome often return 0 size for images because they're loaded in parallel.

My quick and dirty solution was to wrap the code that calls my plugin in a $(window).load() event:

$(document).ready(function() {
    $(window).load(function() {
        $('.magnifier').magnifier();
    });
});

How would I go about implementing this inside the plugin itself? What is the cleanest way to detect that images have loaded so I can measure their dimensions?

Soviut
  • 83,904
  • 44
  • 175
  • 239

2 Answers2

3

Images have a load() event, so you could do something like:

$(document).ready(function() {
    $('.magnifier').magnifier();
});

$.fn.magnifier = function() {
    return this.each(function() {
        $(this).find('img').load(function() {
            // do something to image when it is loaded
        });
    });
}

You could also simply wrap the code around window.load inside the plugin itself:

$.fn.magnifier = function() {
    var that = this;
    $(window).load(function() {
        that.each(function() {
            $(this).find('img').each(function() {
                // image would be loaded at this point
            });
        });
    });
    return this;
}
Paolo Bergantino
  • 466,948
  • 77
  • 516
  • 433
1

I'm not sure I understand completely but this will fire after all images are loaded.

$("img").load(function() { 

});
Andy Gaskell
  • 30,917
  • 5
  • 76
  • 80