Ensuring JavaScript Is Enabled Before Displaying Content On A Web Page

I’ve previously noted that password-protection schemes that depend on JavaScript alone are entirely pointless. No matter how hard you try to obfuscate, mask or hide efforts to protect JavaScript code, anyone with a bit of knowledge and a bit of time on his hands can retrieve and view all your code, including all your username / password pairs.

But it occurred to me recently that, while silly for its stated purpose, I didn’t note how the same technique I demonstrated for a JavaScript login system does have one very valuable, practical application: Requiring users to have JavaScript enabled in order to view your Web page.

As more applications become JavaScript / AJAX dependent, the ability to ensure clients are running JavaScript becomes increasingly important. Fortunately, thanks to CSS-based design, we can easily ensure most clients enable JavaScript by dynamically changing the content of layout divs.

Basically, we lay out a page as though we expect JavaScript to be disabled. Then, we use JavaScript to correct the layout if it is, indeed, activated.

Begin With A CSS-Driven Layout

For maximum efficacy, we begin with a CSS-driven layout. That is, we use the “containers-and-columns” approach: There are divs which act as “container”, then nested divs within those containers which act as columns. The content and site navigation go within the column divs.

Having more than one container allows us to have headers, footers, etc. that are independent of the content; that’s going to help us show special content when JavaScript is not enabled.

So, let’s make our simple layout: One container for the header, one for our warning message, another for column-based content; a fourth for a footer.

<div id="header">
    <h1>Ensuring JavaScript Is Enabled Before <br />
    Displaying Content On A Web Page</h1>
</div>

<div id="warn">
    <p>Your Web browser does not have JavaScript enabled. In order to view this site, you must <a href="https://www.google.com/adsense/support/bin/answer.py?hl=en&amp;answer=12654">enable JavaScript in your browser</a>.
</div>

<div id="main">
    <div id="nav">
        <!-- nav links / text go here -->
    </div>
    <div id="content">
        <h2>This is the main body content.</h2>
        <!-- Site content goes here -->
    </div>
</div>

<div id="footer">
    <p><!-- this is the footer text area --></p>
</div>

And the CSS:

body {
	background: #9CF;
}
#header, #warn, #main, #footer {
	width: 900px;
	margin: 10px auto;
}

#header, #main, #footer {
	background: #fff;
}

#warn {
	background: #ffc;
	border: 1px solid #000;
}

#warn p {
	margin: 0;
	font-weight: bold;
}

#main {
	display: none;
}

#nav {
	float: left;
	width: 300px;
	background: #9c0;
}
#content {
	margin-left: 320px;
}

h1, h2, p {
	margin: 0;
	padding: 5px;
}

Pretty simple and straightforward. The biggest items are note are the existence of div#warn, and the initial CSS setting for div#main. Note that the warning message is styled to act like a header / footer element — that is, to be contained outside the normal content of the page — and div#main has its initial display property set to none. (I also know this layout isn’t very good. It’s quick and dirty for demo purposes.)

What that means is that if we visit the page as it exists now, we’ll see only the header, warning and footer. (Assuming we are using a CSS-compliant browser. This is a safe assumption, since our intent is to drive content via JavaScript, and the entire point behind the exercise is to ensure JavaScript is enabled. If the user agent checking our site doesn’t support CSS, it sure as heck doesn’t support JavaScript, either.)

The JavaScript Function To Ensure JavaScript Is Enabled

Checking whether JavaScript is enabled is as simple as seeing if we can reference JavaScript’s document object.

Remember, JavaScript’s document object refers to the current Web page. Therefore, regardless of the browser being used, any reference we make in JavaScript to document should return the current page; if we can reference the document object, then we know some flavor of JavaScript is currently supported by the browser.

So, we simply create a function called checkJS(), which is called by the body tag’s onload event. checkJS() tries to reference the document object; if it can, it hides div#warn and shows div#main. If it can’t, we are left with the default condition: the warning is visible, the content is not.

function checkJS() {
	if(document) {
		document.getElementById('warn').style.display = 'none';
		document.getElementById('main').style.display = 'block';
	}
}

Yes, it’s literally that simple to do. You can see a working demo here:

http://demo.dougv.com/js_ensure_active/

I distribute all code under the GNU GPL version 3.

A couple of quick notes about this solution:

It still processes all content inside of #main. Any processor- or memory-intensive code you may have on your page will still execute and be rendered. As such, you might want to consider using AJAX to load any content that either depends on JavaScript to properly render or that hogs server resources. You’d do that inside the checkJS() function; after turning #main visible again, you can easily set the innerHTML of #content with AJAX or JavaScript. I’ll leave figuring out how to do that up to you.

The content in #main is just hidden. Anyone looking at the source code of your site will see what’s in #main, and they’ll be able to display it easily, either by using a GreaseMonkey script, a toolbar that allows custom CSS, etc. Again, this is not intended for security; only for the convenience of ensuring JavaScript has been enabled before you render content which requires it.

Alternative syntax for jQuery. If you are using jQuery, you can use $(document).ready() instead of the body’s onload event and the checkJS() function. All you need to do is add this JavaScript to the head section of your page:

$(document).ready(function() {
	$("#warn").css("display", "none");
	$("#main").css("display", "block");
});

All links in this post on Delicious: http://delicious.com/dhvrm/ensuring-javascript-is-enabled-before-displaying-content-on-a-web-page

2 Comments

  1. It’s ok! I’ve noticed your div main is hidden but it is in the html code. I’m working with jsf. Do you know how can I render the elements that I want only if javascript is enabled?

  2. You can always have an empty, “container” div on the page, then use JavaScript to create child elements of that “container” div, e.g., http://www.w3schools.com/dom/met_element_appendchild.asp

    That ensures that JavaScript must be enabled for your content to be seen, but it is very code-intensive.

    I have not worked with JavaServer Faces (I assume that’s the JSF you note), so I can’t suggest any methods to employ that in solving your problem directly.

Leave a Reply

  • Check out the Commenting Guidelines before commenting, please!
  • Want to share code? Please put it into a GitHub Gist, CodePen or pastebin and link to that in your comment.
  • Just have a line or two of markup? Wrap them in an appropriate SyntaxHighlighter Evolved shortcode for your programming language, please!