简体   繁体   中英

Events before $(document).ready

I have a functionality 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.

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";

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/

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM