On lines 3930 through 3947 jQuery version 3.1.1 processes .ready() , called after document already loaded. On line 3938, jQuery.ready is called inside setTimeout without setting a duration with a comment attached
which explains how window.alert('alert 3') could be called before window.alert('alert 2')
// Catch cases where $(document).ready() is called // after the browser event has already occurred. // Support: IE <=9 - 10 only // Older IE sometimes signals "interactive" too soon if ( document.readyState === "complete" || ( document.readyState !== "loading" && !document.documentElement.doScroll ) ) { // Handle it asynchronously to allow scripts the opportunity to delay ready window.setTimeout( jQuery.ready ); // Line 3938 } else { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed ); }
The next stacksnippet should reproduce the result described by OP
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Demo2</title> <script src="https://code.jquery.com/jquery-3.1.1.js"></script> <script> $(window.document).ready(function() { window.alert('alert 1'); }); $(function() { window.alert('alert 2'); }); $(function() { window.alert('alert 3'); }); </script> </head> <body> </body> </html>
See also the completed function on line 3924
// The ready event handler and self cleanup method function completed() { document.removeEventListener( "DOMContentLoaded", completed ); window.removeEventListener( "load", completed ); jQuery.ready(); }
See plnkr http://plnkr.co/edit/C0leBhYJq8CMh7WqndzH?p=preview in version 1
Change, update
To ensure that functions are executed in .ready() , you can return a promise from function calls, use .then() inside a single .ready() call to call functions defined globally or earlier in the .ready() handler.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Demo2</title> <script src="https://code.jquery.com/jquery-3.1.1.js"></script> <script> function ready1(wait, index) { </script> </head> </html>
source share