There are three ways to write the jquery ready function: 1. The complete way of writing "$(document).ready(function(){//ready code});"; 2. The way of omitting document "$(). ready(function(){//ready code});"; 3. The writing method "$(function(){//ready code});" when both document and ready() are omitted.
The operating environment of this tutorial: windows7 system, jquery3.6.1 version, Dell G3 computer.
jquery document ready function
Sometimes, in the Html page, we need to wait for all the Html content of the page to be loaded before executing JS Code, at this time, jQuery provides a function named Document Ready, which can easily solve this problem.
For example:
<script type="text/javascript"> $(document).ready(function () { //文档就绪后直接运行的JS代码 }); </script>
$: jquery flag
onload: Load all the content in the page, including external resources (Pictures, documents, etc. files)
First load all the content and external resources in the page, and then load the js code
ready (document ready function): Loading the page The content does not include external resources ()
First load all the tag content in the page, then load the js code, and finally load the external resources
The following case Code:
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <script src="js/jquery-3.6.1.min.js"></script> <script type="text/javascript"> $(document).ready( function() { //文档就绪后直接运行的代码 function f1() { var div1 = document.getElementById("div1"); div1.innerText = "Hello"; } f1(); }); </script> </head> <body> <div id="div1"></div> </body> </html>
Use jQuery's ready() method to run the code in the HTML document after it is completely loaded, which prevents the search for non-existent elements.
In jQuery, $(document).ready(function () {})
can be omitted as:
$().ready(function(){}) $(function(){});
From In terms of code size, the second type is smaller and is worth recommending.
Judging from the use of the jQuery code above, jQuery makes JS code simpler and has less code, making JS code easier to develop and maintain overall.
Summary: There are three methods of document ready function
The first writing format of document ready function
$(document).ready(function(){ alert("文档就绪函数第一种书写方法"); })
Document ready function The second writing method
$().ready(function(){ alert("文档就绪函数第二种书写方法"); })
The third writing method of document ready function
$(function(){ alert("文档就绪函数第三种书写方法"); })
[Recommended learning: jQuery video tutorial, web front-end video 】
The above is the detailed content of There are several ways to write jquery ready function. For more information, please follow other related articles on the PHP Chinese website!