Events before $(document).ready
I have a functi开发者_如何学运维onality to hide controls conditionally before the document is loaded. If I put this functionality on $(document).ready
, I see the page flickering to hide the controls conditionally. I would like to know if there is an event that can be called before $(document).ready
is triggered.
As others mentioned do something like this
<div id="test" class="hidden"> my hidden div tag </div>
.hidden
{
display:none;
}
in the document.ready , you can show , this is equivalent of onload , which waits till html is loaded
$(document).ready(function() {
$('#test').show();
});
jsfiddle example here
http://jsfiddle.net/kdpAr/
Common issue. Use CSS to have the controls hidden by default and then use JS upon $(document).ready
to decide which controls to make visible. There will be no flicker. It will just look like the appropriate parts of the page are loading progressively.
You can't safely run JS before the document is ready and parts of the document will be visible before you can run JS. So, the only solution is to make sure all non-flicker elements are hidden by default and you then only show the ones you want visible.
The simplest way to do this is to just put a common class on all dynamic elements:
<div id="myControl1" class="initiallyHidden"></div>
and use CSS to make sure they all start out hidden:
.initiallyHidden {display: none;}
And then your javascript will override that when it decides an element should be visible:
document.getElementById("myControl1").style.display = "block";
When I've needed to hide something before Javascript is loaded I would set it hidden in css like so:
display:none;
or:
visibility: hidden;
You can also use conditions in combination with Javascript to reveal it if need be.
call the JavaScript function in next to HTML element
ex:
<span></span>
<script> call JS function</script>
You can just open a script tag right after the HTML you want to hide condionnaly (jQuery must be declared before however) and then call hide directly, not inside a $(document).ready like this :
<div id="toHide">Lorem ipsum</div>
<script type="text/javascript">
$("#toHide").hide();
</script>
You have to put your elements BEFORE running your javascript
<div>hi</div>
<script>
$("div").css('background-color', '#EEE');
</script>
http://sandbox.phpcode.eu/g/d01a1
精彩评论