tags:

views:

117

answers:

7

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?

+4  A: 

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.

Sarfraz
You don't even need that much. You can simply do `$(function() { ... });`
casablanca
`$(document).load()` doesn't work. Test it: http://jsfiddle.net/kjZrn/ You would need `$(window).load()` or `$(document).ready()` (or equivalent shortcut).
patrick dw
A: 

The purpose of

$(document).ready()

is precisely to run code once the document is ready. Or am I missing something?

BoltClock
+6  A: 
$(document).ready(
    function() {
        //code to execute once the page is loaded
    }
);
A. M.
+1 This is a good solution, since it doesn't seem as though OP is worried about images being fully downloaded.
patrick dw
A: 

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.

Dave Ward
A: 

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

 $(document).ready(function() {
   // put all your jQuery goodness in here.
 });
Aaron Saunders
+2  A: 

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).

Joel
A: 
$(function() {
    // document has loaded at this point
});
Bobby Jack