开发者

Preloading images before webpage loads

it's my 1st questio开发者_JAVA百科n here, so pardon if something is asked wrong :) I want to preload 3 images before webpage is loaded so all of them would appear in the same moment. Right now images are loaded one after another and it looks kinda choppy. One image is defined in css (), other two are plain simple "img" element. I've tried creating javascript image objects - images still loads choppy, tried to preload them in display:none; div - still choppy. What should I do?

Thanks.


One simple solution is to use data URIs http://css-tricks.com/data-uris/

http://www.nczonline.net/blog/2010/07/06/data-uris-make-css-sprites-obsolete/

I think that should probably fix it.

data URIs have some limitations as far as IE goes, but I think in this case you should just call it graceful degradation. :)

Edit: I saw your mention display:none divs. Display non divs will NOT preload your images. You need to set the display to block and hide the div in another way. Setting z-index or -9999 offset or some such.


This works: (try it here: http://dl.dropbox.com/u/186012/demos/loadatonce/index.html)

<!-- jQuery is required -->

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

<!-- the images -->
<div class="showmetoo" style="background: url(jimhance-vader_inset.jpg)">
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/></div>

<img class="showall" src="octopus3.jpg" alt="a picture"><br/>
<img class="showall" src="moorea.jpg" alt="a picture"><br/>

<!-- hidden by default -->
<style>
img.showall { visibility: hidden }
div.showmetoo { visibility: hidden }
</style>



<!-- the script -->
<script type="text/javascript">
var remaining = $('.showall').length;

function showthem(){
  remaining--;
  if(!remaining){
    $('.showall').css('visibility', 'visible');
    $('.showmetoo').css('visibility', 'visible');
  }
}

// bind the callback to the load event of the pictures.
$('.showall').bind('load',showthem);

// force the pictures to show (just in case)
setTimeout(showthem, 1000);  //just in case load event fires before callback is set.
</script>


The easiest solution is probably to display a loading gif for all three images until they are all loaded, then replace the gif with the actual image.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜