预隐藏元素是最容易接近的方式

时间:2016-04-11 17:11:58

标签: javascript css internet-explorer rendering visibility

我陷入了两难境地。

我的目标是减少渲染页面时必须重新绘制和回流的数量。到目前为止,我已经通过遵循这种代码格式实现了很多:

<html>
<head>
<title>whatever</title>
</head>
<body>
<div ID="page">
<!-- All visible page content and normal HTML here -->
</div>
<script>
document.getElementById('page').style.visibility="hidden";
// functions to manipulate dom and styles of elements go here
document.getElementById('page').style.visibility="visible";
</script>
</body>
</html>

到目前为止,这种格式适用于包括Internet Explorer 7在内的所有浏览器。但是我看到了一些问题。

当处理页面时(特别是慢动作),整页渲染时没有应用样式加载,然后整个页面在javascript执行时变为白色,然后执行后,页面返回应用样式。

现在我要做的是让那些启用了javascript的用户看到页面空白,直到完成所有操作,然后一次显示所有内容。我试图尽量减少重新粉刷和回流(因为我想在幕后做所有事情)。

这是我迄今为止所想到并尝试过的,但没有成功:

代码#1:

<html>
<head>
<title>whatever</title>
<style>
#page{visibility:hidden}
</style>
</head>
<body>
<div ID="page">
<!-- All visible page content and normal HTML here -->
</div>
<script>
// functions to manipulate dom and styles of elements go here
document.getElementById('page').style.visibility="visible";
</script>
</body>
</html>

此代码无法正常工作,因为启用了CSS且禁用了javascript的用户在页面加载时会看到空白屏幕。我希望所有用户都能看到内容,无论使用何种浏览器或设置。

代码#2:

<html>
<head>
<title>whatever</title>
<script>
var x=document.getElementsByTagName("STYLE")[0];
if(x){
    x.innerHTML+="#WR{visibility:hidden}";
}
</script>
</head>
<body>
<div ID="page">
<!-- All visible page content and normal HTML here -->
</div>
<script>
// functions to manipulate dom and styles of elements go here
document.getElementById('page').style.visibility="visible";
</script>
</body>
</html>

当它涉及innerHTML时,它在Internet Explorer 7中起作用。它声明:

  

线:1   查尔:55   错误:未知的运行时错误   代码:0

然后我尝试了这段代码。

代码#3:

<html>
<head>
<title>whatever</title>
<script>
var x=document.getElementById("WR");
if(x){
    x.style.visibility="hidden";
}
</script>
</head>
<body>
<div ID="page">
<!-- All visible page content and normal HTML here -->
</div>
<script>
// functions to manipulate dom and styles of elements go here
document.getElementById('page').style.visibility="visible";
</script>
</body>
</html>

Internet Explorer 7报告:

  

线:1   Char:1   错误:对象不支持此属性或方法   代码:0

我尝试将document.更改为window.,但仍然收到上述错误。如果我删除了前缀并且只使用了getElementById("WR"),那么我从IE7中收到了一个Object Expected错误。

我有什么办法可以解决这个问题,以便尽可能多的网页浏览器(新旧)启用javascript可以看到整个屏幕空白,当javascript处理完毕后,屏幕重新出现?

此外,我想限制<head></head>之间的javascript数量,因为我在我的网站上有adsense广告,并且我不希望他们的代码在我的HTML中太低我希望我的页面加载速度快。

1 个答案:

答案 0 :(得分:0)

您可以尝试ie7的特殊代码,如此

<!--[if IE 7]>
  <script type="text/javascript">
    // this is only executed for IE 7
  </script>
<![endif]-->

把它放在头部。然后找到解决这个问题的ie 7并将其置于此处

希望这有帮助