Hiding fallback content

Hiding fallback content using javascript is a very common technique. It means that any scenario where javascript isn’t available is automatically handled.

I’ve noticed that on many websites, this fallback content is briefly shown, before the javascript has downloaded and run. It’s not a huge problem, but it’s not ideal. So I’ve created a very simple script that ensures fallback content is only revealed to those without javascript (or when the javascript fails to run).

The first bit of the script is added immediately after the opening <body> tag:

<script>
document.body.className+=' has-js';
var hasjsrm=setTimeout(function(){document.body.className=document.body.className.replace(' has-js','')},5000);
</script>

The first line of javascript adds the class has-js to the body. Your stylesheet should hide fallback content that is a child of .has-js. This content will immediately be hidden. There’s another scenario we are handling in the second line of javascript; what if the main javascript file doesn’t download, or has a parse error? This line will remove the class has-js after 5 seconds.

Now, in our main javascript file, on the very last line, we add this code:

clearTimeout(hasjsrm);
$('body').addClass('has-js');

The first line will cancel that timeout, so the class isn’t removed again. The second line will add the class again incase it was too late. If you aren’t using jQuery for your project, use this script instead:

clearTimeout(hasjsrm);
document.body.className+=' has-js';

That’s all there is to it; pretty simple, and yet bulletproof. If the javascript doesn’t run within 5 seconds the fallback content will be revealed. Otherwise, users will never see this content. If 5 seconds isn’t long enough for your script to run then increase the duration.

You can grab the code and see an example at has-js on GitHub.


Notice: Array to string conversion in /var/www/joshemerson.co.uk/public_html/site/plugins/tags.php on line 22

Fatal error: Uncaught Error: Function name must be a string in /var/www/joshemerson.co.uk/public_html/site/plugins/tags.php:22 Stack trace: #0 /var/www/joshemerson.co.uk/public_html/site/templates/post.php(12): tags(Object(page)) #1 /var/www/joshemerson.co.uk/public_html/kirby/lib/template.php(36): require('/var/www/joshem...') #2 /var/www/joshemerson.co.uk/public_html/kirby/lib/template.php(25): tpl::loadFile('/var/www/joshem...', Array, true) #3 /var/www/joshemerson.co.uk/public_html/kirby/lib/site.php(203): tpl::load('post', Array, true) #4 /var/www/joshemerson.co.uk/public_html/kirby/system.php(65): site->load() #5 /var/www/joshemerson.co.uk/public_html/index.php(71): require_once('/var/www/joshem...') #6 {main} thrown in /var/www/joshemerson.co.uk/public_html/site/plugins/tags.php on line 22