今天早上有个帖子问有多少人禁用JavaScript。然后我开始想知道可以使用什么技术来确定用户是否禁用了它。

有人知道一些简单的方法来检测JavaScript是否被禁用吗?我的意图是给一个警告,如果浏览器没有启用JS,站点将无法正常运行。

最终,我想把它们重定向到能够在没有JS的情况下工作的内容,但我需要这个检测作为一个占位符来开始。


当前回答

我认为你可以在noscript标签中插入一个图像标签,并查看你的站点有多少次以及这个图像被加载的频率。

其他回答

因为我总是想给浏览器一些有价值的东西,我经常使用这个技巧:

首先,页面中任何需要JavaScript才能正常运行的部分(包括通过getElementById调用等修改的被动HTML元素)都被设计成可用的,假设没有可用的JavaScript。(设计得好像它不存在一样)

任何需要JavaScript的元素,我在标签中放置如下内容:

<span name="jsOnly" style="display: none;"></span>

然后在文档的开头,使用.onload或document。在getElementsByName('jsOnly')的循环中设置.style。Display = "";重新打开JS依赖的元素。这样,非JS的浏览器就不需要看到站点中依赖于JS的部分,如果他们拥有它,它会在准备就绪时立即显示出来。

一旦您习惯了这种方法,就很容易混合您的代码来处理这两种情况,尽管我现在只是在试验noscript标记,并期望它会有一些额外的优点。

我过去使用的一种技术是使用JavaScript编写一个会话cookie,它只是作为一个标志,表示启用了JavaScript。然后服务器端代码查找此cookie,如果没有找到,则采取适当的操作。当然,这种技术确实依赖于启用cookie !

在主体上使用.no-js类,并基于.no-js父类创建非javascript样式。 如果javascript被禁用,你会得到所有的非javascript样式, 如果有JS支持,.no- JS类将被替换,像往常一样提供所有的样式。

 document.body.className = document.body.className.replace("no-js","js");

通过modernizr在HTML5样板http://html5boilerplate.com/中使用的技巧,但你可以使用一行javascript来替换类

Noscript标签是可以的,但是为什么在你的HTML中有额外的东西,当它可以用CSS完成时

您会想看一下noscript标记。

<script type="text/javascript">
...some javascript script to insert data...
</script>
<noscript>
   <p>Access the <a href="http://someplace.com/data">data.</a></p>
</noscript>

Why don't you just put a hijacked onClick() event handler that will fire only when JS is enabled, and use this to append a parameter (js=true) to the clicked/selected URL (you could also detect a drop down list and change the value- of add a hidden form field). So now when the server sees this parameter (js=true) it knows that JS is enabled and then do your fancy logic server-side. The down side to this is that the first time a users comes to your site, bookmark, URL, search engine generated URL- you will need to detect that this is a new user so don't look for the NVP appended into the URL, and the server would have to wait for the next click to determine the user is JS enabled/disabled. Also, another downside is that the URL will end up on the browser URL and if this user then bookmarks this URL it will have the js=true NVP, even if the user does not have JS enabled, though on the next click the server would be wise to knowing whether the user still had JS enabled or not. Sigh.. this is fun...