fabjoa
fabjoa

Reputation: 1615

how do you know if document is ready

I have a JavaScript that generates HTML blocks. This script is sometimes called somewhere in run time, and sometimes before document is loaded. I want a script that is able to tell if document is ready. If so, generate the HTML, otherwise, add a document.ready() function. What is jQuery's best way to know if document has been loaded?

Upvotes: 3

Views: 1663

Answers (7)

Michael Lowden
Michael Lowden

Reputation: 103

I just ran into this as well. I have an auto-hide mechanism that triggers too fast while the rest of the document loads (if that's when it's shown in the first place). I solved fairly easily by adding a global boolean that is flipped to TRUE on document.ready().

At the top of my JS:

var documentReady = false;

My onReady funtion:

$(document).ready(function(){
    documentReady = true;
    ...
}

Upvotes: 0

Sarfraz
Sarfraz

Reputation: 382861

Use the load event:

$(window).load(function(){
  // your code...
});

With load event, the DOM, images, frames and any other external resources are loaded into the document.

Upvotes: 4

Bobby Jack
Bobby Jack

Reputation: 16048

$(function() {
    // document has loaded at this point
});

Upvotes: 0

Joel
Joel

Reputation: 21

You can use the ready event to run things after the DOM is loaded

$(document).ready( function() {
  // your function
});

or the load event to wait until absolutely everything is loaded

$(document).load( function() {
  // your function
});

Unless you know you need to use the load event, I would use the ready one (which I believe is the DOMContentLoaded event).

Upvotes: 2

Aaron Saunders
Aaron Saunders

Reputation: 33345

http://www.learningjquery.com/2006/09/introducing-document-ready

 $(document).ready(function() {
   // put all your jQuery goodness in here.
 });

Upvotes: 0

Dave Ward
Dave Ward

Reputation: 60570

It's safe to always wrap that HTML generation code in $(document).ready(). If the document is already ready, a newly registered $(document).ready() callback will execute immediately.

Upvotes: 1

A. M.
A. M.

Reputation: 565

$(document).ready(
    function() {
        //code to execute once the page is loaded
    }
);

Upvotes: 7

Related Questions