Necessity of .ready() in jQuery - javascript

I've seen various examples use this and I'm curious to know, is it dangerous not to wrap jQuery code in the following?
$(document).ready(function () {});
I know what it does and I know why you do it but I'm curious if it is more unsafe or just bad practice/style to not have it? Thanks!

You use it if your code needs to access the DOM.
If you're just setting up classes and modules, but not actually running them, then you don't need to wrap them in the ready handler.
However, if you're doing something that requires elements to be loaded (like, adding event handlers) then you need to do it in the ready() event.
EDIT:
Here is an example: http://jsfiddle.net/ctrlfrk/43n8U/
Try commenting out the addHandler functions and see what happens.
(Note that I've set jsfiddle to run this code in the head tag, by default it usually places the code in the onload event, which negates the need for the ready handler)

It depends on where you are placing your scripts. If you add a script tag just before the closing <body> you don't need to use it because the DOM will already be loaded. On the other hand if you place your script tag inside the <head> section and access the DOM you absolutely need to use it or your script won't work because at the moment your script executes the browser hasn't yet read and parsed the DOM.

See this (already answered)
jQuery ready function aliases
for those that the above is tl;dr; :
Additional reading: http://api.jquery.com/ready/

Wrapping your code in ready() function only delays the running of that code until the page has been loaded. The code does not get "safer" somehow.
But many times you want to run some code that will query the DOM that is created after the script-tag that your code is in, or simply need some structures from the document that are placed after that script tag. If that is the case, then ready() is for you.
But generally there is no valid reason not to use ready() function, so that's why everybode almost always use it.

I think you should also be aware of jQuery's $(window).load() and how it differs from $(document).ready()
Read more about it here

Related

How important it is to wrap jquery code in $(document).ready() function?

I have been developing my frontend code with jQuery for a while now, and since I am implementing the site with partials in rails. Often I would use content_for :javascript to wrap up some code that is specific for a view.
and my question is, I end up with a lot of script tags and since most of them are jquery code, I have typed up a lot of $(document).ready(function() {});
So my question is, whether it is necessary to wrap everything in document.ready, and if I have too many of document.ready will it affect the performance?
$(document).ready() has one purpose - to execute some code after the DOM has finished loading and is now ready for access or modification.
If your code is located before DOM elements such as in the <head> tag or in the top or middle of the <body> section before some DOM elements and that code does attempt to access the DOM upon first initialization, then it should be placed into a $(document).ready() block so it will not execute before the DOM is ready or the ` tag should be moved.
If your code is in a <script> tag within the <body> that is after the DOM elements that it needs to access then your code does not need to be in a $(document).ready() block.
Or, if your code is not called upon initialization (e.g. it's only called later upon other events) or your code does not access the DOM upon initialization, then that code does not need to be inside a $(document).ready() block.
Though you obviously have jQuery available, you can read this answer for a more detailed description: pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it.
Having multiple $(document).ready() blocks is just like registering multiple callbacks for an event. It's really no big deal. Each one just takes an extra couple function calls to setup and is an extra callback execution at execution time. If that's the cleanest way to write your code, then by all means use multiple $(document).ready() blocks.
To summarize, put code into a $(document).ready() block when:
A specific block of code needs to access the DOM when it is first run and the code is located in a script tag that is placed before the end of the <body> tag or is placed before some DOM elements that it might need to access.
There is no need to put code into a $(document).ready() block when:
The part of the code that runs at first initialization does not access the DOM.
The code is placed into a <script> tag that is after the DOM elements that it references.
The <script> tag is marked defer because this explicitly instructs the browser to delay the running of this script tag until after the DOM has been parsed.
Also, keep in mind that it does not matter where functions are declared. It only matters where the functions are called from. So, you can define as many functions as you want outside of $(document).ready(). You just have to make sure that any functions that access the DOM are not called too soon.
If your code does access your DOM element but you put it outside $(document).ready(), it may subject to fail or produce unexpected behavior. See this example below:
var listA = $('ul.myclass').children();
$(document).ready(function(){
var listB = $('ul.myclass').children();
});
From simple snippet above, listA is calculated straightaway when the script is loaded even your document has not been fully loaded or ready, while listB is calculated when the document is loaded and ready.
listA and listB could be different in this scenario even though they are calculated from the same DOM selector.
It's OK for you to initialize some variable values or pre-load some values which have nothing to do with the UI outside of document.ready(). But when you want to initialize your UI or access the DOM upon startup, always do it when the document finishes loading (document.ready).
I agree with everything #jfriend00 says but also remember that not all your code needs to be in the document.ready event. What I mean by that is that you can create your functions at any time, they only need to be executed at document.ready. For instance:
function manipulateDOM( el ) {
document.getElementById(el).classList.add('myClass');
}
$(document).ready(function()){
manipulateDOM('myEl');
});

Is it really necessary to wait for DOM ready to manipulate the DOM?

Is it really necessary to wait for the "ready" (or "window.onload") events if your code only manipulates DOM elements that have already been parsed entirely?
The jQuery documentation for the "ready()" function demonstrates how you could wait to perform actions until the DOM is entirely ready but the example is for code (script tags) that are listed before the DOM elements in question. But it seems that code which appears after the necessary DOM elements in an HTML document has access to them since, presumably, the DOM is built as the browser parses the document.
For example, is it safe to assume that the following code is reliable in all situations or is it still necessary (or beneficial somehow) to use a ready/onload handler?
<body>
<div id="foo"/>
<script type="text/javascript">
var foo = document.getElementById('foo');
foo.innerHTML = 'The element #foo is loaded!';
</script>
</body>
This SO question is very similar but I wanted to bump it to see if there is any more information.
If your JavaScript code is below the DOM elements and only modifies them exclusively, you don't need to wait for the DOM ready event.
However, keep in mind editing a DOM element which contains a script element (or more specifically, before the element's closing tag) used to cause big problems in IE6 (thanks T.J. Crowder) and IE7.
However, this requires inline scripts which can be a maintenance problem. It is preferred to have your JavaScript stored externally (and many speak of the benefits of including them before the closing body tag) for many benefits such as ease of maintenance and fine grained cache control.
in your case it is fine because the browser will render your code line by line and in your code id="foo" comes first so it will get that div....but suppose you wrote this script in head tag then the script will run first and it wont get the div with id="foo" because its not yet loaded..its better to write in document.ready method
Yes, it's safe if you js code is after dom but usually it's not relly good idea to mix html and js.
Document is loaded in linear fashion so your code works correctly.
Sometimes programmers do not use document ready for performance purpose when the javascript is not depends on the DOM below it. Here is some example.

jQuery ready, is it always needed?

Regarding my question here: Validate dynamically added control
Should we always use the ready function on javascripts?
One should only manipulate the DOM when it is guaranteed that such an operation is valid and behaves in a well-defined manner.
Delaying execution until the "document ready event" (jQuery.ready) ensures the DOM is "complete". However, depending upon browser and context, it is quite possible it is not needed -- not something I like to bet on (it also involves more thinking and makes code more dependent upon the HTML/code order).
Happy coding.
JQuery documentation shows this below:
All three of the following syntaxes
are equivalent:
• $(document).ready(handler)
• $().ready(handler) (this is not
recommended)
• $(handler)
Any JQuery starting with $(handler) executes when the DOM is ready. You don't need to worry about the ready bit.
SOURCE: http://api.jquery.com/ready/
No: it is only needed if you need to wait for the DOM to finish loading.
You can also use the "live" function to bind which may decrease page load times as described here
http://encosia.com/2010/08/18/dont-let-jquerys-document-ready-slow-you-down/
Read this
The .ready() method is generally
incompatible with the
attribute. If load must be used,
either do not use .ready() or use
jQuery's .load() method to attach load
event handlers to the window or to
more specific items, like images.
U can Google or search on SO for similar answer
You do not need to use document ready. place your jQuery just before </body> tag and your other jQuery scripts and plugins after your jQuery as such.
<script src="jquery.js"></script>
<script src="other.js"></script>
<script>
$('div').click.....
</script>
</body>
There's a great article about this "don't let document ready slow you down"
Depends the element your workin on, you have many possibilities.
If it's juste for a navigationbar or a module you can chose different DOM elements.
/* for a menu */
$('.menu').ready(function() {...})
/* for the all page */
$(docuement).ready(function() {...})
But you can also include your jquery file and your script at the end of page.
<script src="jquery.js"></script>
<script>
$('.menu').click(function() {...})
</script>

Simple questions about ajax - Help me understand

I need a little help understanding something. I am using the colorbox plugin to load an external an external html snippet (which works fine). But none of my jquery selectors see the newly loaded html. Is that right (I think it is)? and if so how do I work around that.
Thanks
When you set any properties/bind events in your $(document).ready(function() { ... }) they are executed on page load. So it is all applied to the DOM elements that are present initially.
But when you call the AJAX request and insert some elements into your document, the jquery statements are not executed again (because document.ready doesn't fire). Some solutions to overcome this are:
execute the inside of the document.ready function or the relevant part of it after you insert the new elements.
if the only thing you need are event handlers that should be bound the the new elements you may use live events.

Initiate onclick faster than with document.onload

I have html-pages with links where i want to attach a function to their onclick event. One way to do it is of course:
Save
But I know this is not the best practice. So instead I wait for window.onload, loop through the links and attach the save-function to the links with rel="save". The problem with this is that it waits until the whole page has finished loading which can be several seconds after the link is displayed and clickable.
So is there another way to do this? Avoiding onclick in the html but that makes it work immediately when the link is rendered.
Internet Explorer has a handy attribute for <script> tags called defer. It's for delaying the parsing of a script until the document has finished loading. For other browsers that support it, you can use DOMContentLoaded, as someone else suggested and for browsers that don't support either you can fall back to onload.
<script type="text/javascript" defer>
//- Run this code when the DOM parsing has completed
</script>
I did a quick Google search for "DOMContentLoaded defer" and found the following page that might help:
http://tanny.ica.com/ica/tko/tkoblog.nsf/dx/domcontentloaded-event-for-browsers
In your case, you can just leave that as it is. Stick to the simplest possible thing, even if it is not the general best practice.
You could try DOMContentLoaded event instead of load. IE also gives you the defer attribute for script tags, which defers execution until the DOM is loaded. If those don't work for you, then you are stuck with the solutions you mention, as far as I know.
I don't know if this is appropriate for your solution, but you could insert script immediately below the are with the links you need altered. This script would not be wrapped in a function, allowing the browser to execute it immediately when seen. The effect is that you can run script before the full page is loaded, altering only the items that exist above the script being run. (If you reference something below the script, it will fail.)
BTW, this is almost certainly not a best practice, and some would probably label it a worst practice.
How about this?
Save
Note: This solution requires to users to have Javascript enabled. Not exactly best practice, but may be suitable for your scenario.
The ideal here would be to use the ideas of Unobtrusive Javascript.
In this way, if the Javascript isn't loaded the link would still do something. It's a link right, so it leads the user to another piece of content? - this should work without Javascript. And if the functionality attached to the links can ONLY work with Javascript you should create and insert them into the DOM with Javascript (they aren't clickable if they aren't there...).
(Otherwise how about delegating the click event to a wrapper element? Does that work before the element is complete?)
edit: Oh, and "save" sounds very much like it ought to be a button in a form rather than a link. The Unobtrusive JS stuff still applies though.

Categories

Resources