Dimitri Vorontzov
Dimitri Vorontzov

Reputation: 8104

Eliminate fadeIn blink

I am using a rather standard technique for fading in <body> with jQuery while keeping it visible for those users who don't have JavaScript enabled.

In CSS, I set

body.has-js {
    display:none;
}

Then I add .has-js with the following jQuery snippet in the <head> section:

<script>
   jQuery(document).ready(function($) {
       $("body").addClass("has-js");
   });

   window.onload = function() {
      jQuery("body").fadeIn(500);
   }
</script>

The desired result is to make the website initially invisible and then have it fade in smoothly once all the content has loaded.

Problem: apparently, content loads before JavaScript kicks in, so the page flickers briefly before .has-js class is added. This happens in all browsers except Firefox.

Question: how can I eliminate that flicker, while still keeping the site visible to those users who have JavaScript disabled?

Upvotes: 1

Views: 87

Answers (3)

MMM
MMM

Reputation: 7310

Try putting this just after your opening <body>:

<script>
(function () {
    var elements = document.getElementsByTagName("body");
    var body = elements[0];
    body.className = "has-js";
})();
</script>

You don't really need to wait for the DOM to load in your scenario, and whenever this script will be loaded you have a guarantee that at least the body element is available.

In case your body already has a class assigned to it in HTML, replace the final line with the following:

body.className += " has-js";

Upvotes: 4

Jithin
Jithin

Reputation: 2604

I think thats because, the script will add the has-js class to body when document is ready. So put <script>$("body").addClass("has-js");</script> just after <body> tag.

Upvotes: 2

Karl-Andr&#233; Gagnon
Karl-Andr&#233; Gagnon

Reputation: 33870

Instead of using dom ready like that:

jQuery(document).ready(function($) {
    $("body").addClass("has-js");
});

Do something like that :

<head>
</head>
<body>
    <script>
        document.getElementsByTagName('body')[0].className = 'has-js';
    </script>
    <!-- Your content -->
</body>

Like that, when the body tag is created, it had his class before adding the content.

Upvotes: 3

Related Questions