I wrote a simple javascript image rotator which picks a random image on each page load. The issue is that if i use a default image, that default image will show up for a second before the javascript loads and replaces it. Obviously if someone has javascript disabled i want them to see an image. How can i have a default image without a flickering of the default image.
If you hide the default image as the first thing you do when the page loads, there probably won't be a chance for the users to see the image. You can then install an onload handler on the image and change its source to your random image. When the image loads, you can unhide the image.
window.onload = function () {
var img = document.getElementById("rotating_image");
// Hide the default image that's shown to people with no JS
img.style.visibility = "hidden";
// We'll unhide it when our new image loads
img.onload = function () {
img.style.visibility = "visible";
};
// Load a random image
img.src = "http://example.com/random" + Math.floor(Math.random() * 5) + ".jpg";
};
You may also want to consider just putting the JS immediately after the image. This may execute the JS at the point instead of when the page loads. But I'm not sure on this.
<img src="/not/rotated/image.jpg" />
<script type="text/javascript">
// change image
</script>
It sounds like you want to change the page HTML before window.onload fires (because at that point the default image has been displayed already).
You need to attach your javascript function to a "DOMContentLoaded" or commonly called domready event. Dean Edwards provided us a fantastic cross-browser implementation http://dean.edwards.name/weblog/2006/06/again/.
Hope that helps :)