Ready and load events in jQuery, jqueryreadyload

Source: Internet
Author: User

Ready and load events in jQuery, jqueryreadyload
Ready and load events in jQuery (from MOOC)

JQuery has three methods for loading documents.

$ (Document ). ready (function (){//... code ...}) // document ready abbreviation $ (function (){//... code ...}) $ (document ). load (function (){//... code ...})

One is ready and the other is load. What is the difference between the two?

Ready and load:
During the interview, you are often asked the following question: what is the first execution of ready and load? The answer is that ready runs the command first and load the command.

DOM document loading steps:
To understand why ready runs first, you must first understand the loading steps of the DOM document after loading:

(1) parse the HTML structure. (2) Load External scripts and style sheet files. (3) Parse and execute the script code. (4) construct the html dom model. // Ready (5) loads external files such as images. (6) the page has been loaded. // Load

You should have understood the above description. ready will be executed after step (4) is completed, but load will be executed only after step (6) is completed.

Conclusion:

The difference between ready and load lies in the loading of resource files. ready builds a basic DOM structure, so the faster the code is loaded, the better. In the era of high-speed browsing, no one is willing to wait for the answer. If a website page is loaded for more than 4 seconds, sorry, 1/4 of your users will be lost, so the user experience is crucial for the framework. The sooner we handle DOM, the better, we do not need to wait until all image resources are loaded to process frame loading. If there are too many image resources, the load event will not be triggered.

Let's take a look at how jQuery handles document loading timing:

jQuery.ready.promise = function( obj ) {    if ( !readyList ) {        readyList = jQuery.Deferred();        if ( document.readyState === "complete" ) {            // Handle it asynchronously to allow scripts the opportunity to delay ready            setTimeout( jQuery.ready );        } else {            document.addEventListener( "DOMContentLoaded", completed, false );            window.addEventListener( "load", completed, false );        }    }    return readyList.promise( obj );};

JQuery's ready is packaged through promise, which is also a good method of jQuery. It unifies the Callback System and will be highlighted later.
Specific jQuery-compatible policies: For advanced browsers, we are happy to use the DOMContentLoaded event, saving time and effort.

So what should I do with the old IE?

Continue to look at jQuery's solution:

// Ensure firing before onload, maybe late but safe also for iframesdocument.attachEvent( "onreadystatechange", completed );// A fallback to window.onload, that will always workwindow.attachEvent( "onload", completed );// If IE and not a frame// continually check to see if the document is readyvar top = false;try {    top = window.frameElement == null && document.documentElement;} catch(e) {}if ( top && top.doScroll ) {    (function doScrollCheck() {        if ( !jQuery.isReady ) {            try {                // Use the trick by Diego Perini                // http://javascript.nwbox.com/IEContentLoaded/                top.doScroll("left");            } catch(e) {                return setTimeout( doScrollCheck, 50 );            }            // detach all dom ready events            detach();            // and execute any waiting functions            jQuery.ready();        }    })();}

If the browser existsdocument.onreadystatechangeEvent. When this event is triggered, ifdocument.readyState=completeIt can be considered that the DOM tree has been loaded. However, this event is not reliable. For example, when an image exists in the page, it may be triggered only after the onload event. In other words, it can only be correctly executed as an alternative when the page does not contain binary resources or is very small or cached.

Load detection for IE

In 2007, Diego Perini reported a method to check whether IE is loaded and called using the doScroll method. For details, see http://javascript.nwbox.com/iecontentloaded /.
The principle is that when IE is in a non-iframe, it is only possible to continuously judge whether the DOM has been loaded by executing doScroll. In the above process, we tried to execute doScroll at an interval of 50 milliseconds. Note that when the page is not loaded, calling doScroll will cause an exception, so we used try-catch to catch the exception.
Conclusion: In general, when the page DOM is not loaded, an exception occurs when the doScroll method is called. If no exception occurs, the page DOM is loaded.

This is the first time we can handle ready loading. What if ready finishes loading the page?

JQuery must skip binding in this case:

if ( document.readyState === "complete" ) {     // Handle it asynchronously to allow scripts the opportunity to delay ready     setTimeout( jQuery.ready ); }

Check the readyState status to determine whether the page loading is complete. Here, we will give a timer the minimum time to execute, mainly to ensure that the execution is correct.

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.