I want to do:
$(\"img\").bind(\'load\', function() {
// do stuff
});
But the load event doesn\'t fire when the image is loaded from cache
My simple solution, it doesn't need any external plugin and for common cases should be enough:
/**
* Trigger a callback when the selected images are loaded:
* @param {String} selector
* @param {Function} callback
*/
var onImgLoad = function(selector, callback){
$(selector).each(function(){
if (this.complete || /*for IE 10-*/ $(this).height() > 0) {
callback.apply(this);
}
else {
$(this).on('load', function(){
callback.apply(this);
});
}
});
};
use it like this:
onImgLoad('img', function(){
// do stuff
});
for example, to fade in your images on load you can do:
$('img').hide();
onImgLoad('img', function(){
$(this).fadeIn(700);
});
Or as alternative, if you prefer a jquery plugin-like approach:
/**
* Trigger a callback when 'this' image is loaded:
* @param {Function} callback
*/
(function($){
$.fn.imgLoad = function(callback) {
return this.each(function() {
if (callback) {
if (this.complete || /*for IE 10-*/ $(this).height() > 0) {
callback.apply(this);
}
else {
$(this).on('load', function(){
callback.apply(this);
});
}
}
});
};
})(jQuery);
and use it in this way:
$('img').imgLoad(function(){
// do stuff
});
for example:
$('img').hide().imgLoad(function(){
$(this).fadeIn(700);
});