Home>Article>Web Front-end> There are several ways to write jquery ready function

There are several ways to write jquery ready function

青灯夜游
青灯夜游 Original
2022-11-25 20:38:08 1703browse

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.

There are several ways to write jquery ready function

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:

  • $: 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:

       

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.

There are several ways to write jquery ready function

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:What is "+" css selector? Next article:What is "+" css selector?