Problem with javascript image rotator, default image

I wrote a simple javascript image rotator that selects a random image each time the page loads. The problem is that if I use the default image, that default image will be displayed for a second before javascript loads and replaces it. Obviously, if someone turned off javascript, I want them to see the image. How can I get the default image without flickering the default image.

+3
source share
3 answers

It looks like you want to change the HTML of the page before running window.onload (because at this point the default image is already displayed).

javascript "DOMContentLoaded" domready. - http://dean.edwards.name/weblog/2006/06/again/.

, :)

+2

, , , , . onload . , .

window.onload = function () {
    var img = document.getElementById("rotating_image");

    // Hide the default image that 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";

};
0

JS . JS , . .

<img src="/not/rotated/image.jpg" />
<script type="text/javascript">
// change image
</script>
0

Source: https://habr.com/ru/post/1698506/


All Articles