jQuery $(document).ready()
Jakob Jenkov |
Whenever you use jQuery to manipulate your web page, you wait until the document ready event has fired. The document ready event signals that the DOM of the page is now ready, so you can manipulate it without worrying that parts of the DOM has not yet been created. The document ready event fires before all images etc. are loaded, but after the whole DOM itself is ready.
jQuery Document Ready Example
Here is a jQuery document ready listener example:
$(document).ready(function() { //DOM manipulation code });
You call jQuery's $
function, passing to it the document
object.
The $
function returns an enhanced version of the document
object.
This enhanced object has a ready()
function you can call, to which you pass
a JavaScript function. Once the DOM is ready, the JavaScript function is executed.
Inside the function passed to the ready()
method, you can execute all the
jQuery and JavaScript code you need, in order to initialize / enhance the HTML elements
in your page. You will see many examples of this, in the following pages.
Multiple Document Ready Listeners
jQuery allows you to register multiple document ready listeners. Just call $(document).ready()
multiple times. Here is a multiple document ready listener example:
$(document).ready(function() { //DOM manipulation code }); $(document).ready(function() { //DOM manipulation code });
The two listener functions registered in this example will both get called when the DOM is ready. They will get called in the order they were registered.
Registering multiple document ready event listeners can be really useful if you include HTML pages inside other HTML pages (e.g. using server side include features of your backend / web server). You may need some page initialization to occur both in the outer and inner page. Thus both the outer and inner page can register a document ready listener, and perform the page initialization they both need.
Tweet | |
Jakob Jenkov |