How to Randomize Page-Loaders (with a Little jQuery)

Why you would ever want your webpage to have random page loaders each time it is visited is beyond me, but hell, why not.

Creating this effect is fairly easy to achieve in jQuery. All you really need to do is the following:

  1. Create an array of filenames in your .js file corresponding to the names of your preloader gifs.
  2. Use a little math to randomize the file selection.

You can find an example of this preloader-randomizing on my Github Pages for a custom Bootstrap3 template I am building:

Create an Array of Gifs:

In your .js file, create an array of the filenames that correspond to each gif that will act as the page loader. All of these are assumed to be held within the same folder.

var preloadGifs = [‘rubix.gif’, ‘squareFlip.gif’, ‘squareTiles.gif’, ‘squareDiamond.gif’, ‘square5.gif’, ‘gears.gif’, ‘ball.gif’];

Randomize the Selection:

Now all you need to do is randomize the selection of which gif will be used on pageload. To do that, you spell out the path to your preloader folder, and then allow a randomize() function to retrieve the final portion of the path name from the array above, and append it to the end.

$(‘<img class=”fade-in” src=”img/preloader/’ + preloadGifs[Math.floor(Math.random() * preloadGifs.length)] + ‘”>’).appendTo(‘#status’);

Now, every time the page loads, you have a random gif selected from your folder of pageloader gifs! How incredibly useful! [sarcasm]

Useful or not, sometimes its worth doing things just because you find it interesting. The same idea can be applied to randomly selecting other things, like background images, that will be different each time the page loads.

Again, you can find a demo of this RIGHT HERE. Just reload the page a few times to see it in action.