Preloading images for HTML games using PxLoaderPosted on: May 23, 2012

I've had the opportunity at work to do some development on a couple of HTML games (with the conscious attempt to move away from flash and make them work on mobile devices). One of the issues I ran into was that I was getting a FOUC due to the resources for these games taking a while to load. Enter the amazing PxLoader which solved all my preloading problems.

The next issue I had was that the game was still in development, so I had to keep adding to the list of images to preload. I eventually got fed up with this and figured there must be a way I can script my way out of this headache (and future proof for future development). So what I came up with works as follows: Scan the directory that has the images and make that available to my JS, then pass PxLoader the list, and go from there.

"What about the code?" I hear you cry... well fear not... here it is:

Download and include both the 'PxLoader.js' and 'PxLoaderImage.js' files in your <head>, then put the following before your '</head>':

<script type="text/javascript">
<?php
	// This will be the path to the images on the file system (ie: NOT a url)
	$images = scandir('/path/to/images/');
	$images = array_filter($images, function($var) {
		// Filter out:
		// * directories
		// * anything beginning with a '.' (ie: '.', '..', '.DS_Store', etc...)
		if ( is_dir( '/path/to/images/'.$var ) || substr( $var, 0, 1 ) === '.' ) {
			return false;
		}
		return true;
	});
	$images = "'".implode("','", $images)."'";
	echo "var IMAGES_TO_PRELOAD = [".$images."];";
>
</script>

Then put the following into your JS file (which you'll need to execute after the above or on DOM ready):

var loader = new PxLoader();
for ( i = 0; i &lt; IMAGES_TO_PRELOAD.length; i++ ) {
	// This will be the static URL to the image.
	loader.addImage( '/path/to/images/'+IMAGES_TO_PRELOAD[i] );
}

loader.addProgressListener(function(e) {
	var percent = Math.round( e.completedCount / e.totalCount * 100 );
	// Use the 'percent' variable to display the progress to the user
});
loader.addCompletionListener(function() {
	// Work your magic here
});
loader.start();

... and there you have it. You can now drop in images to your heart's content without having to worry about whether your resource loader knows about them (note: I only needed to scan for images one level deep, so you might have to modify the code to better suit your purposes).

As always: feel free to let me know what you think below.