javascript - jQuery image preload order -
i'm having troubles adapting jquery image preload script in 1 aspect: can't figure out how ensure, images loaded/displayed in order of image array.
at moment every time reload page images displayed in different order. (everything except image order works fine alreday.)
can me fixing this?
the relevant code:
(function($) { var imglist = []; $.extend({ preload: function(imgarr, option) { var setting = $.extend({ init: function(loaded, total) {}, loaded: function(img, loaded, total, bild) {}, loaded_all: function(loaded, total) {} }, option); var total = imgarr.length; var loaded = 0; setting.init(0, total); (var = 0; < total; i++) { imglist[i] = ($("<img />") .attr("src", imgarr[i]) .load(function() { loaded++; setting.loaded(this, loaded, total, this.src); if(loaded == total) { setting.loaded_all(loaded, total); } }) ); } } }); })(jquery); $(document).ready(function() { $(function() { $.preload([ "image1.jpg", "image2.jpg", "image3.jpg" ], { init: function(loaded, total) { var z = 0; while (z < total) { z++; $("section nav").append('<img id="e'+z+'" src="all/blank.png" alt=""/>'); } }, loaded: function(img, loaded, total, bild) { $("#e"+loaded).prop("src",bild); }, loaded_all: function(loaded, total) { //all done! } }); }); }); update:
in end solved different, shorter script wrote scratch. starts adding (very small) dummy images placeholders image container array contains real images , loads each image after previous 1 finished:
imgs = new array("number1.png","number2.png","number3.png"); (i=0; i<imgs.length; i++) { $("section nav").append('<img id="e'+i+'" src="blank.png" alt=""/>'); } fin(0); function fin (n) { $('#e'+n).attr('onload', 'fin('+n+')'); $("#e"+n).attr("src", imgs[n]).load( function() { fin ((n+1)); }); }
the problem append loaded img position of number of images loaded, i.e. images placed in order loaded.
you want them ordered on var i :
for (var = 0; < total; i++) { imglist[i] = ($("<img />") .attr("src", imgarr[i]) .load(function() { loaded++; setting.loaded(this, i, total, this.src); // instead of loaded if(loaded == total) { setting.loaded_all(loaded, total); } }) ); } but won't work since i same total @ time image loaded, images go position total. not want!
so need wrap in self calling anonymous function access correct i value:
for (var = 0; < total; i++) { // wrap in function access right (function(img) { imglist[img] = ($("<img />") .attr("src", imgarr[img]) .load(function() { loaded++; setting.loaded(this, img, total, this.src); // img instead of if(loaded == total) { setting.loaded_all(loaded, total); } }) ); })(i); } replace loop 1 , should work.
Comments
Post a Comment