Triggering domready by force in jQuery?

5.1k views Asked by At

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?

3

There are 3 answers

0
David Hellsing On BEST ANSWER

jQuery.ready();

6
NickFitz On

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 ;-)

0
user435779 On

I had a closely related question, I ended up finding the answer myself right before resorting to posting to SO. As people who have my question will likely land here (number one google result for "jquery force document ready"), allow me to give some extra info.

My problem is that I am dynamically generating some HTML (using XSLT) that will sometimes be saved for later, but other times I just want to open a new window with the new HTML so the user can preview it. Like so:

var html = UseXSLTToGenerateSomeHTML();
var myWindow = window.open('', '', 'width=805,height=493');
myWindow.document.write(html);
myWindow.focus();

Problem is, the generated HTML uses jQuery, and the domready event was never getting invoked. It should have been obvious to me immediately from David's answer how to do it, but the tweak escaped me momentarily. It is:

var html = UseXSLTToGenerateSomeHTML();
var myWindow = window.open('', '', 'width=805,height=493');
myWindow.document.write(html);
myWindow.focus();
mywindow.jQuery.ready();

Note that in this case, the page doing this doesn't even use jQuery... only the generated HTML does. Doesn't matter, you are generating the jQuery event on the other document.