views:

402

answers:

2

Since placing javascript DOM methods in the bottom of the html page (after <body>) is a lot faster than using the jQuery 'ready' event, shouldnt we be forcing it by doing:

$('document').trigger('ready');

...after the body tag? I havent really tried this, but it should speed up things. Or did I miss something?

+1  A: 

The ready event means the document has now been parsed and the DOM is available to be manipulated. That happens when the browser has completed its parsing, and you can't make it happen sooner.

How do you think such a thing would work? Would it flip a magic switch in the browser's HTML parser that makes it run faster than it normally does? Would it cause the computer's processor to run faster, so the browser would finish parsing the document sooner?

You can't force the browser to parse the document any faster than it's going to anyway. Not even with jQuery ;-)

NickFitz
Thats not really true, is it? http://stackoverflow.com/questions/1438883/jquery-why-use-document-ready-if-external-js-at-bottom-of-pageWe use a domReady() function in the bottom on our client sites and we never run into any problems. In fact, it's just a lot faster than using the 'ready' state and can manipulate the DOM without any problems, since it's loaded anyway.
David
That wasn't the question though. The OP was asking about *triggering* the `ready` event, but that's impossible: you can trigger events that are associated with user activity such as `click` to simulate the user clicking a button, but you can't trigger an event that depends on the browser's internal representation of the DOM having reached a given state. Rephrase the question as asking about `$('document').trigger('load');` and it should be obvious that it doesn't make sense.
NickFitz
Of course you can trigger events that is not related to any user activity. I think you can trigger the ready event by using jQuery.ready(); or jQuery(document).triggerHandler("ready");
David
@David: you may be able to trigger execution of the *function* associated with that event, but that doesn't mean the event has actually happened yet. I can cause the `onload` handler to be executed using `window.onload();` but that doesn't mean the document has loaded.
NickFitz
Yes, but that is exactly my point. There is no "native" DOMContentLoaded event in IE, jQuery just simulates it using the IE dom ready trick described at http://javascript.nwbox.com/IEContentLoaded/ . So my question was if I can trigger the function myself by adding $.ready() before closing the body tag, to make the domReady happen as soon as possible. My tests show pretty good results doing so.
David
In that case surely all you're doing is calling the function by a rather convoluted means. There's no need for all this mucking about "triggering" pseudo events - just call the function directly.
NickFitz
+1  A: 

jQuery.ready();

David