I have been using this chunk of code to programmatically check if Javascript is available and use different behavioral CSS.
If Javascript is disabled, it will only show a normal unordered list.
If javascript is enabled, the list will be transformed after page load and then displayed to the user (avoiding the possible redraw/flicker of the unordered list element before/during transformation).
Is it possible that document.getElementsByTagName('body') can actually return an empty array at this stage of the page rendering, or is it always available?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Title</title>
<style type="text/css">
.javascript ul { display:none; }
.no_javascript ul { display:block; }
.transformed { background-color: yellow; }
</style>
</head>
<body class="no_javascript">
<script type="text/javascript">
// Inform us that javascript is available
(function() {
var body = document.getElementsByTagName('body');
if ( body && body[0] ) {
body[0].className = body[0].className.replace(/no_javascript/, "javascript");
}
})();
</script>
<ul>
<li>Option 1</li>
<li>Option 2</li>
<li>Option 3</li>
</ul>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".javascript ul").addClass("transformed").css('display','block');
});
</script>
</body>
</html>
Update: http://stackoverflow.com/questions/463670/how-to-eliminate-post-render-flicker seems like a duplicate of my question. It was the problem I was trying to solve properly.