$ (document). The difference between ready and window.onload "turn"

Source: Internet
Author: User

In jquery, we can see two ways of writing: $ (function () {}) and $ (document). Ready (function () {})

Both of these methods have the same effect, which is to execute a function after the DOM document tree has been loaded (note that the document tree inside does not load all of the files).

Instead, Window.onload executes a function after the DOM document tree has been loaded and all files have been loaded. That is, $ (document). Ready is executed before window.onload.

So jquery inside $ (document). How is the inside of the ready function implemented? Let's take a look at the following:

Let's add a ready function to the document:

Document.ready = function (callback) {///compatible Ff,google if (Document.addeventlistener) { Document.addeventlistener (' domcontentloaded ', function () {Document.removeeventlistener (' Domcontentl                    Oaded ', Arguments.callee, false);                Callback (); }, False)}//compatible with IE else if (document.attachevent) {document.attachevent ( ' onReadyStateChange ', function () {if (document.readystate = = "complete") {
Document.detachevent ("onReadyStateChange", Arguments.callee);
Callback ();
}})} else if (Document.lastchild = = document.body) {callback (); } }

$ (document). Ready this function is implemented. Let's try to verify that the "Ready is going to be performed before OnLoad" is the top of the list:

   Window.onload = function () {            alert (' onload ');        };        $ (document). Ready (function () {            alert (' Ready ');        });

After executing this code, you will see that the browser pops up "ready" and the onload pops up.

Let's try it yourself!

$ (document). The difference between ready and window.onload "turn"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.