Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 324
Abishek Avatar asked Aug 20 '11 17:08

Abishek


People also ask

What happens before document ready?

The document ready event fired when the HTML document is loaded and the DOM is ready, even if all the graphics haven't loaded yet.

What is the difference between the $( document .ready and window onload events?

The $(document). ready() is a jQuery event which occurs when the HTML document has been fully loaded, while the window. onload event occurs later, when everything including images on the page loaded.

How do you call a function before document ready?

If you simply call a function in the head tag it will execute immediately, before the DOM is even parsed (that's the 'problem' that ready solves). Show activity on this post. Just call your function before the document ready statement.

What comes after document ready?

So, there is no event called after document. ready(). You'll need to create and wait for events to complete on your own, or use window. load().


2 Answers

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/

like image 131
kobe Avatar answered Oct 13 '22 18:10

kobe


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";
like image 33
jfriend00 Avatar answered Oct 13 '22 18:10

jfriend00