Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
350 views
in Technique[技术] by (71.8m points)

javascript - Why document.ready is used in jQuery

What is the exact use of $(document).ready() in jQuery and can we have two $(document).ready() in a webpage?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A page can't be manipulated safely until the document is "ready." Generally people write <script> tags in the starting of the document, in the <head> even before the <body> is written. So, technically, if you are manipulating something from the <body> contents, it is not present at the time of execution.

So, jQuery's $( document ).ready() waits for the HTML Document content to be loaded fully and become ready, after rendering all the elements into the window object or in a nutshell, completes the loading of the body.

Then whatever content present in the code is executed, once the HTML document is fully loaded, which makes sure every HTML element is present as you execute your JS code.

Check out:

And about binding two ready handlers, why do you need two? You can combine the code in a single function. You must give a minimal code to explain. I assume you have something like this:

$( document ).ready( function () {
    // Code block 1 start...
    alert( "First Function..." );
    // Code block 1 end...
});

$( document ).ready( function () {
    // Code block 2 start...
    alert( "Second Function..." );
    // Code block 2 end...
});

And yes, the above is possible. Also, there's no difference from the above having:

$( document ).ready( function () {
    // Code block 1 start...
    alert( "First Function..." );
    // Code block 1 end...

    // Code block 2 start...
    alert( "Second Function..." );
    // Code block 2 end...
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...