Live data from Hacker News

Faster than jQuery(document).ready() - Wait Until Exists

javascriptisawesome.blogspot.nl

11–19 of 19 posts

Re: Faster than jQuery(document).ready() - Wait Until Exists

#13
post #11

.ready() is actually pretty smart and a lot faster than most people give it credit for.

care to elaborate a little bit?

Here's a good summary of what's great about .ready(): http://docs.jquery.com/Tutorials:Introducing_$%28document%29...

Basically, this is what makes it so great: Everything that you stick inside its brackets is ready to go at the earliest possible moment — as soon as the DOM is registered by the browser.

Waiting on the window is actually slower than waiting on the DOM.

Re: Faster than jQuery(document).ready() - Wait Until Exists

#14
post #11

.ready() is actually pretty smart and a lot faster than most people give it credit for.

care to elaborate a little bit?

I don't know that it's all that smart. It uses the DOMReady event in all modern browsers, and uses a load of tricks to get the same behaviour in older browsers. It will never fire before the DOM is ready, like the function in the article does.

Re: Faster than jQuery(document).ready() - Wait Until Exists

#16
Or you could use the built-in setInterval() function to poll for the DOM element and not have to worry about attaching an event handler to a deprecated event. It's expensive, but will only happen in between the time that this code is interpreted and the DOM element loads. And you could easily write something to check for timeout in case is takes too long.

var intID = setInterval(function() { if($("myDOMElement").length || checkForTimeOut()) { clearInterval(intID); doSomething(); } }, 100);

...if it starts lagging just increase the interval time (that last integer).

Re: Faster than jQuery(document).ready() - Wait Until Exists

#18
post #4

Good Idea. Unfortunately the underlying technique the author has used to achieve this (DOM mutation events) is flawed, deprecated and non-optimal. https://developer.mozilla.org/en-US/docs/DOM/Mutation_events "Adding DOM mutation listeners to a document profoundly degrades the performance of further DOM modifications to that document (making them 1.5 - 7 times slower!). Moreover, removing the listeners does not revers…

Came here to say this.

http://updates.html5rocks.com/2012/02/Detect-DOM-changes-wit...

Re: Faster than jQuery(document).ready() - Wait Until Exists

#19
post #14

Earlier quoted context omitted.

care to elaborate a little bit?

I don't know that it's all that smart. It uses the DOMReady event in all modern browsers, and uses a load of tricks to get the same behaviour in older browsers. It will never fire before the DOM is ready, like the function in the article does.

If you don't want to wait for the DOMReady event, you can always write it like so:

(function($) { // $() will work as an alias for jQuery() inside of this function })(jQuery);

Post reply on HN