When should I use jQuery's document.ready function? - javascript

I was told to use document.ready when I first started to use Javascript/jQuery but I never really learned why.
Might someone provide some basic guidelines on when it makes sense to wrap javascript/jquery code inside jQuery's document.ready?
Some topics I'm interested in:
jQuery's .on() method: I use the .on() method for AJAX quite a bit (typically on dynamically created DOM elements). Should the .on() click handlers always be inside document.ready?
Performance: Is it more performant to keep various javascript/jQuery objects inside or outside document.ready (also, is the performance difference significant?)?
Object scope: AJAX-loaded pages can't access objects that were inside the prior page's document.ready, correct? They can only access objects which were outside document.ready (i.e., truly "global" objects)?
Update: To follow a best practice, all my javascript (the jQuery library and my app's code) is at the bottom of my HTML page and I'm using the defer attribute on the jQuery-containing scripts on my AJAX-loaded pages so that I can access the jQuery library on these pages.

In simple words,
$(document).ready is an event which fires up when document is
ready.
Suppose you have placed your jQuery code in head section and trying to access a dom element (an anchor, an img etc), you will not be able to access it because html is interpreted from top to bottom and your html elements are not present when your jQuery code runs.
To overcome this problem, we place every jQuery/javascript code (which uses DOM) inside $(document).ready function which gets called when all the dom elements can be accessed.
And this is the reason, when you place your jQuery code at the bottom (after all dom elements, just before </body>) , there is no need for $(document).ready
There is no need to place on method inside $(document).ready only when you use on method on document because of the same reason I explained above.
//No need to be put inside $(document).ready
$(document).on('click','a',function () {
})
// Need to be put inside $(document).ready if placed inside <head></head>
$('.container').on('click','a',function () {
});
EDIT
From comments,
$(document).ready does not wait for images or scripts. Thats the big difference between $(document).ready and $(document).load
Only code that accesses the DOM should be in ready handler. If it's a plugin, it shouldn't be in the ready event.

Answers:
jQuery's .on() method: I use the .on() method for AJAX quite a bit
(dynamically creating DOM elements). Should the .on() click handlers
always be inside document.ready?
No, not always. If you load your JS in the document head you will need to. If you are creating the elements after the page loads via AJAX, you will need to. You will not need to if the script is below the html element you are adding a handler too.
Performance: Is it more performant to keep various javascript/jQuery
objects inside or outside document.ready (also, is the performance difference significant?)?
It depends. It will take the same amount of time to attach the handlers, it just depends if you want it to happen immediately as the page is loading or if you want it to wait until the entire doc is loaded. So it will depend what other things you are doing on the page.
Object scope: AJAX-loaded pages can't access objects that were inside
the prior page's document.ready, correct? They can only access objects
which were outside document.ready (i.e., truly "global" objects)?
It's essentially it's own function so it can only access vars declared at a global scope (outside/above all functions) or with window.myvarname = '';

Before you can safely use jQuery you need to ensure that the page is in a state where it's ready to be manipulated. With jQuery, we accomplish this by putting our code in a function, and then passing that function to $(document).ready(). The function we pass can just be an anonymous function.
$(document).ready(function() {
console.log('ready!');
});
This will run the function that we pass to .ready() once the document is ready. What's going on here? We're using $(document) to create a jQuery object from our page's document, and then calling the .ready() function on that object, passing it the function we want to execute.
Since this is something you'll find yourself doing a lot, there's a shorthand method for this if you prefer — the $() function does double duty as an alias for $(document).ready() if you pass it a function:
$(function() {
console.log('ready!');
});
This is a good reading: Jquery Fundamentals

.ready() - Specify a function to execute when the DOM is fully loaded.
$(document).ready(function() {
// Handler for .ready() called.
});
Here is a List of all jQuery Methods
Read on Introducing $(document).ready()

To be realistic, document.ready is not needed for anything else than manipulating the DOM accurately and it's not always needed or the best option. What I mean is that when you develop a large jQuery plugin for example you hardly use it throughout the code because you're trying to keep it DRY, so you abstract as much as possible in methods that manipulate the DOM but are meant to be invoked later on. When all your code is tightly integrated the only method exposed in document.ready is usually init where all the DOM magic happens. Hope this answers your question.

You should bind all actions in document.ready, because you should wait till the document is fully loaded.
But, you should create functions for all actions and call them from within the document.ready. When you create functions (your global objects), call them whenever you want. So once your new data is loaded and new elements created, call those functions again.
These functions are the ones where you've bound the events and action items.
$(document).ready(function(){
bindelement1();
bindelement2();
});
function bindelement1(){
$('el1').on('click',function...);
//you might make an ajax call here, then under complete of the AJAX, call this function or any other function again
}
function bindelement2(){
$('el2').on('click',function...);
}

I appended a link to a div and wanted to do some tasks on the click. I added the code below the appended element in the DOM but it did not work. Here is the code:
<div id="advance-search">
Some other DOM elements
<!-- Here I wanted to apppend the link as <span class="bold">x</span> Clear all-->
</div>
<script>
$("#advance-search #reset-adv-srch").on("click", function (){
alert('Link Clicked');``
});
</script>
It did not work. Then I placed the jQuery code inside $(document).ready and it worked perfectly. Here it is.
$(document).ready(function(e) {
$("#advance-search #reset-adv-srch").on("click", function (){
alert('Link Clicked');
});
});

he ready event occurs when the DOM (document object model) has been loaded.
Because this event occurs after the document is ready, it is a good place to have all other jQuery events and functions. Like in the example above.
The ready() method specifies what happens when a ready event occurs.
Tip: The ready() method should not be used together with .

Related

Is jQuery supposed to be used only in the ready event handler?

I have read code the uses jQuery outside of the ready handler, what are the drawbacks, if any to using it this way? For whatever reason I feel uncomfortable with it coded this way.
Inline script from and ASP.NET MVC View:
<script type="text/javascript">
function foo() {
if ($("#checkAll").attr("checked")) {
$(".setColumns").attr("checked", true);
}
else {
$(".setColumns").attr("checked", false);
}
}
</script>
There aren't really any drawbacks. It's just that you need to wait for the DOM element to be loaded before it can be manipulated. For example, if you had code like this:
<script type="text/javascript">
console.log($('#el').html());
</script>
<div id="el">Text</div>
The function would not return a value because the div was not yet loaded.
It is not.
The only reason why some people run it inside the document.ready handler, is because at that time, they can be sure the DOM tree is completely loaded, and your queries will return the correct results.
However, if you put your script tags underneath all elements, you normally would not have any issues with this.
The reason of using jQuery within the DOM ready handler is that event binding will only work when the element is present — if your DOM is not ready, your element may not be present and therefore the event may not be bound.
It is the same problem that people face when trying to bind events to dynamically loaded content without the .on() selector, for example — if the element is not initially present, events will not be bound to it.
p/s: You are of course free to define functions outside the handler.

Why $(function(){...})?

Example 1
Example 2
...Both of these use (from what I can tell) jquery's clone on a function block, as the outermost element of the script. Why is it done this way? What would be lost if that were omitted?
P.S. Is this like instantiating an object from a class?
It is needed to call the function when the document is ready.
As of http://api.jquery.com/ready/
$(document).ready(function() {
// Handler for .ready() called.
});
Which is equivalent to calling:
$(function() {
// Handler for .ready() called.
});
that obviously is equal to
jQuery(function() {
// Your code using failsafe $ alias here...
});
here jQuery is used instead in order to not conflict with $ in case it's used by another library.
This is basically the DOMReady event. The function with your code is the code to be executed when the DOM is ready, but before all resources are loaded.
This ensures that all the HTML elements in your source code would be ready for manipulation in JS. Otherwise you may miss elements that are otherwise in your source code when trying to select them.

jQuery document.ready

I am a little confused with document.ready in jQuery.
When do you define javascript functions inside of
$(document).ready() and when do you not?
Is it safe enough just to put all javascript code inside of $(document).ready()?
What happens when you don't do this?
For example, I use the usual jQuery selectors which do something when you click on stuff. If you don't wrap these with document.ready what is the harm?
Is it only going to cause problems if someone clicks on the element in the split second before the page has loaded? Or can it cause other problems?
When do you define javascript functions inside of $(document).ready() and when do you not?
If the functions should be globally accessible (which might indicate bad design of your application), then you have to define them outside the ready handler.
Is it safe enough just to put all javascript code inside of $(document).ready()?
See above.
What happens when you don't do this?
Depends on what your JavaScript code is doing and where it is located. It the worst case you will get runtime errors because you are trying to access DOM elements before they exist. This would happend if your code is located in the head and you are not only defining functions but already trying to access DOM elements.
For example, I use the usual jQuery selectors which do something when you click on stuff. If you don't wrap these with document.ready what is the harm?
There is no "harm" per se. It would just not work if the the script is located in the head, because the DOM elements don't exist yet. That means, jQuery cannot find and bind the handler to them.
But if you place the script just before the closing body tag, then the DOM elements will exist.
To be on the safe side, whenever you want to access DOM elements, place these calls in the ready event handler or into functions which are called only after the DOM is loaded.
As the jQuery tutorial (you should read it) already states:
As almost everything we do when using jQuery reads or manipulates the document object model (DOM), we need to make sure that we start adding events etc. as soon as the DOM is ready.
To do this, we register a ready event for the document.
$(document).ready(function() {
// do stuff when DOM is ready
});
To give a more complete example:
<html>
<head>
<!-- Assuming jQuery is loaded -->
<script>
function foo() {
// OK - because it is inside a function which is called
// at some time after the DOM was loaded
alert($('#answer').html());
}
$(function() {
// OK - because this is executed once the DOM is loaded
$('button').click(foo);
});
// OK - no DOM access/manipulation
alert('Just a random alert ' + Math.random());
// NOT OK - the element with ID `foo` does not exist yet
$('#answer').html('42');
</script>
</head>
<body>
<div id="question">The answer to life, the universe and everything</div>
<div id="answer"></div>
<button>Show the answer</button>
<script>
// OK - the element with ID `foo` does exist
$('#answer').html('42');
</script>
</body>
</html>
The document.ready handler is triggered when the DOM has been loaded by the browser and ready to be manipulated.
Whether you should use it or not will depend on where you are putting your custom scripts. If you put them at the end of the document, just before the closing </body> tag you don't need to use document.ready because by the time your script executes the DOM will already be loaded and you will be able to manipulate it.
If on the other hand you put your script in the <head> section of the document you should use document.ready to ensure that the DOM is fully loaded before attempting to modify it or attach event handlers to various elements. If you don't do this and you attempt to attach for example a .click event handler to a button, this event will never be triggered because at the moment your script ran, the jQuery selector that you used to find the button didn't return any elements and you didn't successfully attach the handler.
You put code inside of $(document).ready when you need that code to wait for the DOM to load before executing. If the code doesn't require the DOM to load first to exist, then you can put it outside of the $(document).ready.
Incidentally, $(function() { }) is short-hand for $(document).ready();
$(function() {
//stuff here will wait for the DOM to load
$('#something').text('foo'); //should be okay
});
//stuff here will execute immediately.
/* this will likely break */
$('#something').text('weee!');
If you have your scripts at the end of the document, you dont need document.ready.
example: There is a button and on click of it, you need to show an alert.
You can put the bind the click event to button in document.ready.
You can write your jquery script at the end of the document or once the element is loaded in the markup.
Writing everything in document.ready event will make your page slug.
There is no harm not adding event handlers in ready() if you are calling your js functions in the href attribute. If you're adding them with jQuery then you must ensure the objects these handlers refer to are loaded, and this code must come after the document is deemed ready(). This doesn't mean they have to be in the ready() call however, you can call them in functions that are called inside ready() themselves.

jQuery scripts no longer run on partially refreshed elements

I have a number of jQuery scripts that select elements within the area that I run a partial page refresh on.
I am using this css tricks code snippet to refresh that part of the page:
$('#refreshbutton').click(function() {
var url = "http://myUrl.com/indexTest.php?ID=" + Math.random();
setTimeout(function() {
$("#maindisplay").load(url+" #maindisplay>*","");
}, 100);
});
The problem is that the elements within #maindisplay are changed, thus are considered new elements in the dom. Since the scripts that select those elements and attach functions to them run at domready and not during the partial refresh, this poses a problem.
So far I have been unable to find a way to reattach the scripts to the elements within #maindisplay after I partially refresh it.
My question is: What is the optimal way to reattach the scripts to the refreshed area of the page.
Thank you for any advice.
You need to use the live() function to attach your click handler.
You have the following options that I can think of:
Put the attach in a function and call that function on page refresh
Use the .live() functionality
Use .delegate() functionality
Put the Javascript reference to the functionality in a reference in the refresh so that it executes as a part of that refresh
Put the function in the callback
make it part of your setTimeout
some other creative method I did not think of...
Just a note: I would look at the .delegate() with contextual selection added in recent versions (available in 1.4.2 for instance).
Does load() not take a callback function as it's second argument? Why not reattach event handlers to the elements with that function?
$('#result').load('ajax/test.html', function() {
//reattach event handlers here.
});

second $(document).ready event jQuery

I'm using some external jQuery with $(document).ready() to insert adverts after the document ready event has fired, something like:
$(document).ready( function() {
$('#leaderboard').html("<strong>ad code</strong>");
});
This is to prevent the UI being blocked by the slow loading of the adverts. So far it's been working well.
Now I need to insert some more ads though our CMS system, this can't be part of the external JS file, so I'm wondering can I use a second document ready event and insert it using an inline script tag? If so, what will be the order of execution the external JS document ready event first or the inline script?
You can use as many event methods as you want, jquery joins them in a queue. Order of method call is same as definition order - last added is last called.
A useful thing may be also that, you can load html code with script using ajax and when code is loaded into DOM $().ready() also will be called, so you can load ads dynamically.
Yes, adding multiple $(documents).ready()s is not a problem. All will be executed on the ready event.
Note however that your code sample is wrong. $(document).ready() takes a function, not an expression. So you should feed it a function like this:
$(document).ready( function() {
$('#leaderboard').html("<strong>ad code</strong>");
});
That function will be executed when the document is ready.
Here's a little tutorial on Multiple Document Ready
An added bonus of the jQuery way is
that you can have multiple ready()
definitions. This is the case with all
jQuery events.
$(document).ready(function () {
alert("Number One"); });
$(document).ready(function () {
alert("Number Two");
JQuery calls the ready functions in the order they are defined.
If you want to load some data first and deleay execution use holdReady().

Categories

Resources