Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Enforce order of execution of document.ready() calls

I'm working on a codebase with multiple blocks of code setting some behavior on document.ready() (jQuery). Is there a way to enforce that one specific block is called before any of the others?

Background: I need to detect JS errors in an automated testing environment, so I need the code that starts logging JS errors to execute before any other JS code executes.

like image 641
Ankit Soni Avatar asked Jun 04 '12 15:06

Ankit Soni


People also ask

What is the purpose of jQuery document ready () handler?

jQuery ready() Method The ready event occurs when the DOM (document object model) has been loaded. Because this event occurs after the document is ready, it is a good place to have all other jQuery events and functions. Like in the example above. The ready() method specifies what happens when a ready event occurs.

What is difference between $( function () and document Ready?

So technically they are both the same. Not major difference between these two declaration. They used based on weather you use JavaScript then you should use $(document). ready declaration in other case you use jQuery library which is a part of JavaScript then you should use $(function) declaration.

Why do we start our code with document ready () in jQuery?

ready() function will load as soon as the DOM is loaded and before the page contents are loaded. You should wrap all your javascript code with this function to ensure that the code only runs when the page is fully rendered.

What is $( document .ready () and $( window .load () in jQuery?

ready() and $(window). load() event is that the code included inside onload function will run once the entire page(images, iframes, stylesheets,etc) are loaded whereas the $(document). ready() event fires before all images,iframes etc. are loaded, but after the whole DOM itself is ready.


1 Answers

document.ready() callbacks are called in the order they were registered. If you register your testing callback first, it will be called first.

Also if your testing code does not actually need to manipulate the DOM, then you may be able to run it as the code is parsed and not wait until the DOM is ready which would run before the other document.ready() callbacks get called. Or, perhaps you could run part of your testing code immediately and defer only the part that uses the DOM until document.ready().

Another idea is (for testing purposes only) you could run with a slightly modified version of jQuery that added a flag to document.ready() that when passed and set to true indicated to call that function first or you could add a new method document.readyFirst() that would call your function first. This would involve minor changes to the document.ready() processing code in jQuery.

like image 131
jfriend00 Avatar answered Oct 01 '22 03:10

jfriend00