Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent jQuery onload flicker unobtrusively?

I'm using jQuery UI Tabs. How should I prevent the flicker of loading content while also making sure that the content is visible when javascript is disabled?

I've tried adding a .js class to the body when the doc is loaded but as the tabs are loaded at the same time as the class being added there is still the flicker of content.

#container{display:none;}

<div id="container">
  <div id="tabs">
    <ul>
      <li><a href="#tabs-1">Nunc tincidunt</a></li>
      <li><a href="#tabs-2">Proin dolor</a></li>
    </ul>
    <div id="tabs-1">
       <p>Tab 1</p>
    </div>
    <div id="tabs-2">
      <p>Tab 2</p>
    </div>
  </div>
</div>
<script>
$(document).ready(function(){
  $('#tabs').tabs();
  $('#container').show();
});
</script>
like image 859
Asa Carter Avatar asked Jun 01 '12 13:06

Asa Carter


Video Answer


2 Answers

this is what I do. put a class of no-js on your html tag and then put the following code just after the html tag:

<script>
    // Sets 'js' on html element and removes 'no-js' if present (here to prevent flashing)
    (function(){
        document.documentElement.className = document.documentElement.className.replace(/(^|\s)no-js(\s|$)/, '$1$2') + (' js '); 
    })();
</script>

This method allows you to have other classes on your html tag if required. Use the no-js class in your styles for pages that don't have js enabled.

styles example:

#container {
  display:none;
}
.no-js #container
{ 
  display: block;
}
like image 85
Dave Haigh Avatar answered Sep 21 '22 12:09

Dave Haigh


<html class="nojs">
  ...
  <head>
     <script>
       document.documentElement.className = "js";
     </script>
  </head>

  ...
  <style>
  #container {display:none;}
  .nojs #container { display: block;}
  </style>

this will make your content visible even when js is not available on your device. This approach is almost the same performed by H5BP + Modernizr and, as aside benefit, it will prevent the JS FOUC (flash of unstyled content due to js later execution).

like image 26
Fabrizio Calderan Avatar answered Sep 20 '22 12:09

Fabrizio Calderan