开发者

JQuery.ready is too late: How do I apply CSS Values with JQuery before Rendering?

I want to be able to apply opacity to some elements to make them invisible only if javascript is enabled. I don't want to use display:none because I want the layout to act as if they're in the DOM, so setting opacity to 0 is perfect.

I want to be able to set this initial value using Javascript, using JQuery, so I don't have to mess with browser differences on the opacity (and many other) attributes. But if I set opacity to 0 like so:

$(document).ready(function() {
  $("#header").css("opacity", 0);
  $("#header").animate({opacity:1}, 500);
});

...half the time it's already visible on the screen, so it appears and disappears.

How do I set these css values using JQuery before they ever can render?

Looking for a JQuery only solution so 开发者_高级运维I don't have to manually handle every browser implementation like this:

#header {
  -moz-opacity:.50;
  filter:alpha(opacity=50); 
  opacity:.50;
}


Just set opacity to 0 in CSS file itself. To cover the scriptless, add the following to your head:

<noscript><style>#header { opacity: 1; }</style></noscript>

Update: since that's not an option, the next option would be to execute the script directly after the #header element.

<div id="header"></div>
<script>$("#header").css("opacity", 0).animate({opacity:1}, 500);</script>


Why not use

#header
{ 
    visibility: hidden;
}

and then in a noscript in the head

<noscript><style type="text/css">#header { visibility: visible; }</style></noscript>


The problem is that JavaScript execution will almost always happen after rendering begins, unless you do a table hack that prevents rendering until the page is fully downloaded. But then you'll annoy your users, and you should be shot.

You're asking for something that just can't be reliably done without annoying the user. So your better bet is to annoy the developer, and do some extra work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜