当Javascript可用时,才隐藏html [英] Hide html only when Javascript is available

查看:181
本文介绍了当Javascript可用时,才隐藏html的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想这是更多的关于SEO比希望支持浏览器禁用Javascript。我有Javascript / jQuery代码,读取一些html,基本上显示它更好。 html实际上是删除的(在jQuery的 .remove()函数)。



html,所以当页面加载时没有任何视觉工件。但现在我只想隐藏它,如果Javascript启用。我想最简单的事情是在< head> 中添加一些Javascript,将 display:none

解决方案



有没有更好的方法来处理这种情况? div>

任何JavaScript只有在JavaScript被启用时才能工作,所以无论你如何使用JavaScript,它将始终工作,只有当JavaScript启用,所以你从来没有必要测试。



有人说,你可以在 HTML5 Boilerplate 中看到它是如何完成的:

 < html class =no-jslang =en> 
...页面的其余部分
< / html>

使用 no-js < html> 标记。该类稍后将使用JavaScript删除,并添加 js 类,这两个类都可以在CSS和HTML中使用:

 < p class =js>如果启用了JavaScript,则会显示


< p class =no-js>如果JavaScript已停用,则会显示此项< / p>

或在CSS中:

  .no-js #someWidget {display:none; } 
.js #someFallback {display:none; }

如果您使用 Modernizr ,那么它已经为你改变了这些类,但即使你不这么做,你所要做的就是:

  document.documentElement.className = 
document.documentElement.className.replace(/ \bno-js\b /,'js');

这是一个简单而优雅的解决方案,你需要担心的是CSS样式和标记。


I guess this is more about SEO than wanting to support browsers with Javascript disabled. I have Javascript/jQuery code that reads in some html and basically displays it much nicer. The html is actually removed (with jQuery's .remove() function) during the process.

So I hide the html so there aren't any visual artifacts as the page loads. But now I want to only hide it if Javascript is enabled. I guess the easiest thing is to have some Javascript in <head> that adds the display: none css rule to the appropriate elements.

Is there a better way for dealing with this situation?

解决方案

Any JavaScript will only work if JavaScript is enabled so no matter how you do it using JavaScript it will always work only if JavaScript is enabled so you never have to test for that.

That having been said, you can see how it is done in the HTML5 Boilerplate:

<html class="no-js" lang="en">
... the rest of the page
</html>

using a no-js class applied to the <html> tag. The class is later removed using JavaScript and a js class is added, both of which you can use in your CSS and HTML:

<p class="js">This is displayed if JavaScript is enabled</p>
<p class="no-js">This is displayed if JavaScript is disabled</p>

Or in CSS:

.no-js #someWidget { display: none; }
.js #someFallback { display: none; }

If you're using Modernizr then it will already change those classes for you, but even if you don't then all you have to do is something like:

 document.documentElement.className =
     document.documentElement.className.replace(/\bno-js\b/,'js');

It's a simple and elegant solution and all you have to worry about is CSS classes in your styles and markup.

这篇关于当Javascript可用时,才隐藏html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆