📜  jquery on ready - Javascript (1)

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

jQuery on Ready - Javascript

jQuery on ready is a popular method in jQuery that allows developers to execute a code block when the DOM (Document Object Model) is fully loaded. In simple terms, it ensures that the HTML document is ready to manipulate before running a script.

Syntax

The syntax for jQuery on ready is as follows:

$(document).ready(function(){
  // code block to be executed
});

It can also be written in short by using the $() method:

$(function(){
  // code block to be executed
});

Both of the above methods are equivalent and will execute the code block once the DOM is fully loaded.

Why is it important?

The use of jQuery on ready is important because it ensures that scripts don't run before the HTML document is fully loaded. This can prevent errors and unexpected results from occurring in the application.

Examples
Basic example

In the following example, we use jQuery on ready to show an alert box when the page is fully loaded:

<body>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function() {
      alert("Page is fully loaded");
    });
  </script>
</body>
Use in a function

The following example shows how to use jQuery on ready in a function that can be called later:

function doSomething() {
  // code to be executed when the DOM is fully loaded
}

$(document).ready(doSomething);
Multiple functions

jQuery on ready allows you to execute multiple functions when the DOM is fully loaded. The following example shows how to use multiple functions with jQuery on ready:

$(document).ready(function() {
  function func1() {
    console.log("Function 1");
  }
  
  function func2() {
    console.log("Function 2");
  }
  
  func1();
  func2();
});

In this example, we have defined two functions (func1 and func2), and both of them are executed when the DOM is fully loaded.

Conclusion

jQuery on ready is an important method in jQuery that ensures scripts run only after the HTML document is fully loaded. It can also be used to execute multiple functions when the DOM is loaded.