Does this code need to be in a document.ready? - javascript

The document.ready is used to execute code after the DOM is fully loaded. This can be used to attach event handlers to elements on the page e.g
$(function(){
$('#somediv').click(function(){
});
})
<div id="somediv"> </div>
Internally, jQuery hooks up to DOMContentLoaded and window.onload as a fallback. In IE's case an attempt is made to scroll the viewport over and over until successful.
I have a few questions, my first one being, when binding event handlers to the document itself, is it necessary to put that code in a document.ready ? I have always been writing the code below without wrapping it in a document.ready
$(document).keydown(function(e){
if (e.which == 39) {
alert( "right arrow pressed" );
return false;
}
});
And as you can see, it works. My understanding is, since this code doesn't hook up to any elements within the document, but the document itself, there's no need to wrap it in a document.ready handler. Another reason i don't wrap it is because i used to do the same in vanilla javascript the equivalent would be the code below, which also works.
document.onkeydown = function(){
var keyCode = event.keyCode || event.which;
if (keyCode == 39) {
alert( "right arrow pressed" );
return false;
}
}
I've seen numerous posts where people wrap it in a document.ready, is there any downside of not wrapping this code in document.ready ?
Also i think this question stems from my lack of clarity of what happens during this time when the DOM is being constructed, so if someone can explain what happens during the period right before the DOM is ready. To me the document is ready when the html has been parsed and converted into a DOM tree, or is there more to it ?
In summary, here are my questions
When binding event handlers to the document itself, is it
necessary to put that code in a document.ready.
Are there any downsides to not wrapping the code in the document.ready ?
What sequence of events take place when the document is being constructed, right before the document.ready is fired ?

If you are binding to the document itself, you don't need to wait until it is ready. There shouldn't be any downsides to not wrapping it in document.ready in this case.
document.ready gets fired when the DOMReady event is triggered by the browser, or when a specific test is successful for versions of browsers that don't support the DOMReady event.
Additional information. (5/22/12)
Most modern browsers implement the DOMContentLoaded event which fires when all elements defined on the document are ready to be manipulated by javascript. Other browsers either rely on a setTimeout loop that continuously checks the readystate of the document or binds directly to the onreadystatechanged method of the document (taken from jquery core). The document itself is ready to be manipulated before javascript is ever executed, therefore you never need to wait when binding directly to the document.
The only gotcha here is that if the code interacts with elements other than the document, there is a chance that the event could be triggered on the document before those elements exist. It is very unlikely for that to happen, but it can happen. If that is something that can happen with your code, then it makes sense to place it inside of $(document).ready() to prevent that scenario. Your sample doesn't warrant being placed inside of $(document).ready().

The point of $(document).ready is to execute code after the entire document has been parsed.
You only need to use it if you want to use elements that don't exist yet.
(eg, if your script is in the <head>)
If the elements you're using already exist (either because they're global or because your <script> is below them), you don't need it.

The only drawback of not binding an event to the document in a document.ready block would be that it will be possible to fire the event before all the page content has been loaded, which may not be what you want.

This event gets triggered when the DOM hierarchy has been fully
constructed i.e. all assets such as images have been completely
received.
You asked:
When binding event handlers to the document itself, is it necessary to put that code in a document.ready?
Answer: Nope. When using code that rely on the value of CSS style properties, it's important to reference external stylesheets or embed style elements before referencing the script in which your code resides or just before document.ready() block.
Are there any downsides to not wrapping the code in the document.ready ?
Answer: No. But when you've to create elements inside your documents by using JavaScript, then should wait for sake until your DOM gets ready. For this, you should put your code inside document.ready() block.
What sequence of events take place when the document is being constructed, right before the document.ready is fired ?
Answer: Before document.ready gets fired, DOMContentLoaded is already triggered by browser.

When using actions to elements or calling them (that will be generated in DOM or don't exist yet) you need to use $(document).ready

In addition to the answers: you can mere use jquery live function (instead of keydown, etc.) to be free of the situation 'DOM elements must be finished'.
So the next must work properly:
$( "#somediv" ).live( 'keydown', function(){ ... } );
In this case jQuery binds the event when it is possible. You don't have a pain to place all bindings in one (ready) function, your bindings can be placed in independent parts of your HTML page or Javascript files.
So, the result answer is: no, you don't need to place your code in document.ready when you use the mentioned function.
Update
In the last versions of jQuery (>= 1.7) use on() function instead of live() because the last one is depricated. So, it's not necessary to place event bindings into ready().

1. When binding event handlers to the document itself, is it necessary to put that code in a document.ready?
No. In fact, the 'on' methods for binding in JQ can delegate at the document so you could use those at any time on any element safely as long as there wasn't a lot of bubbling being stopped at container elements with stopPropagation.
2. Are there any downsides to not wrapping the code in the document.ready?
Only that scripts in the head might try to hit HTML that isn't there yet. The converse is that HTML might be ready and getting events from the user before the doc is. See 'on' methods or google 'event delegation' for having your cake and eating it too where events are concerned (the caveat is libraries that use stopPropagation stupidly). document.ready is mostly just a way to be certain your code is firing when the HTML is ready to be hit. It's not necessary for code that falls at the bottom of the body tag unless (maybe) you're hitting body itself with something.
3. What sequence of events take place when the document is being constructed, right before the document.ready is fired ?
At the point that document ready is fired, all tags have been parsed and the layout dimensions have been established. Images do not need to have fully loaded, and I'm only guessing, but I suspect non-layout impacting CSS may not be in effect yet in some browsers. An element is considered 'ready' when its closing tag has been read and executed on by the HTML parser. JS in script tags must be handled by an interpreter before HTML parsing can continue, which is why we tend to put our code at the bottom of the doc nowadays anyway, for faster perceived loading time.

Related

Inline Event handler messing with event handler in separate JavaScript file

Could something in the code of an inline event handler like in the HTML markup affect some code or prevent it from firing code in a JavaScript file that is later called. Suppose the JavaScript file contained something like this.
$(a).click(function() {
//some code
}
someJavaScriptCode isn't meant to be valid JavaScript syntax. It is generated by the PrimeFaces library.
My event handler in the JavaScript file works once, but any subsequent clicks after that; it doesn't fire. The code in the inline event handler still works however. I didn't make up the inline code; it was web application's UI library doing that. I'm just wondering how I can make the code above still work.
If your inline code has an error in it, and it is executed before the JavaScript in your javascript file, then it will halt javascript execution which would prevent your external file javascript from running.
I hope this helps.
Are you using a framework that re-renders your DOM? It seams that when you click the element, it is replaced and it looses the event that is applied in your JavaScript file.
If that is the case, place your event on a parent that is not being re-rendered, and target the element this way:
$( parent ).on( 'click', 'a', function (e) {})
The second argument in the "on" method will target any selector and apply the click even, even if the content of the parent is refreshed.

Can I suspend jquery ready event until my script execution is finished?

I have some problem, I have to do some regex replacement to document.innerHTML on page load. but all jquery plugins and jquery method cannot detect body's child elements, I want to rescan document.body object after my regex replace operation. though Not a resonable solution, I did this with jquery as
$("body").html($("body").html());
after body.innerHTML replacement,
It works, jquery method can detect newly changed elements, but it also effect scripts within body tag causing double triggering plugins and requesting script file to server again. I want jquery to detect modified body's element. To do so, can I suspend $(document).ready() event till body's content is updated or is there other technique to reload document.body object. Please don't refer to delegate() on() and live() methods. I know usage of these methods, I don't want to use this approache, I just want jquery to detect modified elements in body, Please help me, thanks alot.

Event fired when browser comes out of "loading" state?

Whenever we go to a website, the browser enters a "loading" state (spinner in place of favicon) till the site is loaded.
Which jquery event is fired when browser comes out of the "loading state"?
$(document).ready(function() {
// put all your jQuery goodness in here.
});
you can try anyone of :
window.onload or document.ready
It would definitely help if you explained what you were trying to do. But since you asked for an jQuery event that fires when the browser has loaded the page, I would suggest you use the jQuery ready handler.
All three of the following syntaxes are equivalent:
$(document).ready(handler)
$().ready(handler) (this is not recommended)
$(handler)
The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code.
EDIT: Since we need an event when the browser has completed loading the page and all its resources, the jQuery .load() method would be more suitable.
The load event is sent to an element when it and all sub-elements have been completely loaded. It is a shortcut for .bind('load', handler).

document.write and delegated event handler persistence

I'm just testing out replacing a whole page with another page using JavaScript and I found this answer with document.write. As to why document.write, I needed to replace the entire HTML, including scripts and styles using the same page.
It does what I want but i can't seem to have consistency with my event handlers. My handlers are all attached to document using:
$(document).delegate(...);
Currently, I have weird results. In a fiddle I made, it attaches a handler. When clicked, the event fires, rewrites the page, runs the function again - but it doesn't attach the handler.
However in my project, I'm doing the same routine (d.w(), then add handlers). It does reattach once and handlers work, but after doing a second routine (still on the same page), it doesn't attach anymore.
So my questions are:
When using d.w(), do existing handlers get erased from document?
Are window as well as document the same after subsequent d.w()s? or are they somehow "renewed"
Do scripts that are already parsed stay in memory and run after subsequent d.w()s? Or do they get erased as well?
(The following applies to google chrome)
Only the document is cleared, the scripts in memory still stay the same. You can easily test it by setting something to a variable and see if it exists after clearing out the document with .open.
The old native handler is therefore lost from the document, but jQuery still thinks that the handler exists in its own event model. You can see it by editing the log to:
console.log('patch', JSON.stringify($.cache ));
jQuery only ever attaches a single native handler per event, so if you have a "click" event registered on document, further handlers attached with jQuery don't attach a new native handler, instead the handler is pushed into the jQuery internal handlers array.
Now, because document.open removed the native handler, but doesn't clear javascript, jQuery still thinks the native handler exists, and further .delegate only goes to the jQuery internal handler array. If you replace your handler with plain old document.onclick you will see it starts working.
You can also keep using jQuery if you add $(document).unbind() (or more robust $.cache = {};, but this is internal and subject to change) before the .delegate, so that jQuery is again synced. Otherwise it won't be, since it has no idea you called document.open.
So:
Yes
They are still the same objects, can be tested by saving a reference and checking that agaist document after a .open
They stay in memory.
http://jsfiddle.net/wphzt/4/
The only reason it stops working from second time onwards is because in your function you have written
document.write('<span>'+(++i)+'</span>');
In which case, next time the document doesn't have the delegate function to increment the span value but has only what you have written in the code snippet I have highlighted above. Thus, as you doubted, yes they get erased as well. Hope this helps.

Call a function on DOM ready from outside <head>?

In jQuery you can wrap all your code in $(function() { ... }); and have it fire when the DOM is ready, but what if you want to put that in the middle of the page somewhere? Isn't it possible that the DOM ready event will fire before it processes that chunk of code and it'll get missed? Is there a way to guarantee it'll get fired?
You can place a <script>..</script> block anywhere in your code:
if you use .ready() (or equivalent syntax) to execute code when the dom is loaded, it will be executed when the whole page is loaded, no matter where you placed the ready() handler.
if you simply put code within the <script> tags, then it will be executed whenever the parser reaches that point of the code.
No, it is not possible for the DOM ready event to fire when the DOM is not ready. It will be fired, regardless of where you place your script.
DOM ready doesn't fire until the whole DOM tree has been loaded, so it will work.
Also, if you happen to do $(function() { ... }) after DOM ready has already fired, jQuery is smart and will just execute your callback right away.
No, the DOM ready event should not get fired until the DOM is ready, meaning until it processes the last closing tag and constructs the DOM fully.
You should be fine placing your <script> tags with the jQuery ready anywhere in the page.
DOM ready event will fire before it processes that chunk of code
only if connection to web-server will fails before the browser download the whole html page.
In such a strange case dom ready event will fires, but your inline scripts fails.

Categories

Resources