egis
egis

Reputation: 1412

Preloading images before webpage loads

it's my 1st question 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.

Upvotes: 3

Views: 5872

Answers (4)

Aakash
Aakash

Reputation: 23717

I noticed that my image was very-high resolutions - more than what is needed for webpages - something like 4500 X 6000 - with a size of ~300kB. So, I adjusted the size with an image editing tool and watered the size down 400 X 600 with a size of ~50kB. Now the image loads quite fast and doesn't show a blank space while its loading.

Upvotes: 0

Sebastián Grignoli
Sebastián Grignoli

Reputation: 33432

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>

Upvotes: 1

Mark
Mark

Reputation: 33561

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.

Upvotes: 2

jdc0589
jdc0589

Reputation: 7018

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.

Upvotes: 1

Related Questions