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
2010-08-23 16:05:25
You don't even need that much. You can simply do `$(function() { ... });`
casablanca
2010-08-23 16:12:46
`$(document).load()` doesn't work. Test it: http://jsfiddle.net/kjZrn/ You would need `$(window).load()` or `$(document).ready()` (or equivalent shortcut).
patrick dw
2010-08-23 16:19:07
A:
The purpose of
$(document).ready()
is precisely to run code once the document is ready. Or am I missing something?
BoltClock
2010-08-23 16:06:20
+6
A:
$(document).ready(
function() {
//code to execute once the page is loaded
}
);
A. M.
2010-08-23 16:10:45
+1 This is a good solution, since it doesn't seem as though OP is worried about images being fully downloaded.
patrick dw
2010-08-23 16:20:57
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
2010-08-23 16:11:33
A:
http://www.learningjquery.com/2006/09/introducing-document-ready
$(document).ready(function() {
// put all your jQuery goodness in here.
});
Aaron Saunders
2010-08-23 16:11:59
+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
2010-08-23 16:12:54