WWW FAQs: How do I detect JavaScript in the user's browser?

2006-06-02: If all you need is alternative content for users who don't have JavaScript turned on, or the ability to show them a simple "turn on JavaScript to use our web application" message, the <noscript> element does a great job:

JavaScript is turned off in your web browser. Turn it on to take full advantage of this site, then refresh the page.

If you want to present completely separate sites to users who have JavaScript and users who don't, just make the non-JavaScript home page the default... and include a snippet of JavaScript code that redirects to the JavaScript-enabled page. For best results, put this code in the head element of your page, where it can be executed before your non-JavaScript page is fully rendered to the user:

window.location = "http://www.mysite.com/javascript-enabled.html";

Some have suggested using a <meta> element in the <noscript> element to redirect users who don't have JavaScript. Alas, while this is very clever, it doesn't work properly. In my tests, Windows Internet Explorer endlessly refreshes the page in a vicious, noisy loop... even if JavaScript is enabled. Ouch! So I recommend redirecting the JavaScript users instead.

"But isn't there a JavaScript function to tell me if JavaScript is turned on or not?"

if (true) {
  document.write("JavaScript is turned on!");

OK, so that's a joke. Or is it?

I get this question surprisingly often. Just think about it for a minute: if JavaScript is turned off, how would your JavaScript code ever get called in the first place? It couldn't be, of course.

When JavaScript is turned on, JavaScript code runs! When JavaScript is turned off, it doesn't. At all. Period. That's what "JavaScript is turned off" means. So there's nothing to test and nowhere to test it.

That's why we use either the noscript element, to present alternative content when JavaScript is turned off, or the "redirect to a new page with JavaScript" trick, to present an alternative page when JavaScript is turned on.

Legal Note: yes, you may use sample HTML, Javascript, PHP and other code presented above in your own projects. You may not reproduce large portions of the text of the article without our express permission.

Got a LiveJournal account? Keep up with the latest articles in this FAQ by adding our syndicated feed to your friends list!