ドキュメント

Events/ready

From jQuery JavaScript Library

Jump to: navigation, search

« Back to Events

ready( fn )

Binds a function to be executed whenever the DOM is ready to be traversed and manipulated.

This is probably the most important function included in the event module, as it can greatly improve the response times of your web applications.

In a nutshell, this is a solid replacement for using window.onload, and attaching a function to that. By using this method, your bound function will be called the instant the DOM is ready to be read and manipulated, which is when 99.99% of all JavaScript code needs to run.

There is one argument passed to the ready event handler: A reference to the jQuery function. You can name that argument whatever you like, and can therefore stick with the $ alias without risk of naming collisions.

You can have as many $(document).ready events on your page as you like. The functions are then executed in the order they were added.

Note: Please make sure that all stylesheets are included before your scripts (especially those that call the ready function). Doing so will make sure that all element properties are correctly defined before jQuery code begins executing. Failure to do this will cause sporadic problems, especially on WebKit-based browsers such as Safari.

Arguments:
fnFunction
The function to be executed when the DOM is ready.
function callback(jQueryReference) {
  this; // document
}
Examples:

Display a message when the DOM is loaded.

$(document).ready(function () {
    $("p").text("The DOM is now loaded and can be manipulated.");
});

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  
  <script>
  $(document).ready(function(){
    $(document).ready(function () {
    $("p").text("The DOM is now loaded and can be manipulated.");
});
  });
  </script>
  <style>p { color:red; }</style>
</head>
<body>
  <p>
  </p>
</body>
</html>

To run code when the DOM loads, write:

$(document).ready(function(){
  // Your code here...
});

To use both the shortcut for $(document).ready() and the argument to write failsafe jQuery code using the $ alias, without relying on the global alias, write:

jQuery(function($) {
  // Your code using failsafe $ alias here...
});

Commonly written as:

$(function() {
  // Your code here...
});

NameType