📜  document.ready() - Javascript (1)

📅  最后修改于: 2023-12-03 15:30:32.871000             🧑  作者: Mango

Introduction to document.ready() - JavaScript

document.ready() is a jQuery method that allows the execution of events once the DOM hierarchy (HTML structure) has been fully loaded.

Why use document.ready()?

Using document.ready() ensures that your code executes only after the entire DOM hierarchy has been loaded, including all your images and assets. This is especially important when your code relies on the dimensions and positions of HTML elements.

Syntax
$(document).ready(function(){
  // Code to execute when the DOM is fully loaded
});

The document.ready() method is attached to the jQuery object ($) and takes a function argument. The function passed as an argument acts as an event handler and will only execute once the DOM hierarchy is fully loaded.

Shorter syntax

The document.ready() method can also be used in an even shorter syntax. The following expressions are identical:

$(document).ready(function(){
  // Code to execute when the DOM is fully loaded
});

// Shorter syntax (equivalent)
$(function(){
  // Code to execute when the DOM is fully loaded
});
Example
```html
<!doctype html>
<html>
  <head>
    <title>document.ready() example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
      $(function(){ // Shorter syntax for document.ready()
        console.log("DOM is fully loaded!");
        
        // Code to execute...
      });
    </script>
  </head>
  <body>
    <h1>My webpage</h1>
    <p>Welcome to my webpage!</p>
    <img src="myimage.jpg">
  </body>
</html>

In the above example, the console will output "DOM is fully loaded!" once the page finishes loading. The code inside the `$(function(){})` function will only execute after the DOM hierarchy (including the image) has been fully loaded.

## Conclusion

Using `document.ready()` is considered a best practice when writing JavaScript and jQuery code. It ensures that your code always executes after the entire DOM hierarchy has been loaded, making sure that the dimensions and positions of HTML elements are accurate.