jquery - How to wait for images loaded with javascript? -
i have div in appending imgs. images loading ajax 20 items. showing jquery animation. problem animation retarding. think there 2 problems:
- images showing not downloaded , want display them now
- when set css display: block img, delay when browser painting image
so question how wait pack of images (20 items) downloaded , how dispose of painting delay?
p/s. if show empty divs (just set them background-color) or 1 image img-tags animation works quickly.
you can use snippet. doesn't depend on library , working our projects.
/* * preload image if not cached, call callback function * @param {string} image url * @param {function} callback function */ function loadimg(url, fn) { var img = new image(); img.src = url; if (img.complete) { // if image has been cached, call callback if (fn) fn.call(img, true); } else { img.onerror = function() { // if fail load image if (fn) fn.call(img, false); }; img.onload = function() { // if loaded if (fn) fn.call(img, true); //on ie6, multiple frames in image fire 'onload' event multiple times. set null img.onload = null; }; }; }
for scenario, can pass in callback function like:
var callback = function(loaded) { if (loaded === true) { // animation. var img = this; // `this` points image itself. } else { // show default image or 'image failed load'. } }
Comments
Post a Comment