De Valdez

Icon

an experiment in brain capacity

JS Image Preloading

When it comes to image preloading, developers have a couple of options to choose from. The easiest and most popular is typically a combination of CSS properties. Some approaches load the desired image as a background-image for a hidden element. Some make use of sprites and background-position. But sometimes CSS won’t suite yer’ fancy. For instance, images loading to a page dynamically which originate from a CMS. In this example, it would be extremely difficult and not very useful to use sprites. You could potentially use hidden background-images but if you need a higher level of control over that image in the DOM this technique may be for you.

Let’s assume you’re going to store the images in JSON format like so.

<script>
	images = [
	  <?php for ($i=0 ; $i <= count($cms_images); $i++) : ?>
			{
			  "id":"1",
			  "title":"Title <?= $i ?>",
			  "image_uri":"<?= $cms_images[$i]['location']) ?>",
			}
		<?= ($i < count($cms_images)) ? ',' : ''; endfor; ?>
	];
</script>

Now that you have a nice structure and the pertinent information, you’re able to create the image on the fly.

<script>
  pic = Array(); for (var i=0; i < images.length; i++) {
    pic[i]       = new Image();
    pic[i].src = images[i]['image_uri'];
  };
</script>

For optimal performance, place these snippets in the head.

Category: JavaScript

blog comments powered by Disqus