You should be randomising the gallery on the server before delivering the web page. If the page is being generated from PHP then simply shuffle() the array the gallery images are in.
If you have an array of the images in JavaScript that you want in random order then you can shuffle them easily as well if you add a shuffle method -
http://javascriptexample.net/extobjects13.php