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.
Related
For example:
<iframe onload="functionName('id-name', 'http://domain.com');"/>
versus
$('#id-name').load(functionName('id-name', "http://domain.com');
(Actually... is my jQuery right?)
UPDATE: Thanks, all, for the responses. I'm using:
$('#id-name').load(function() {
functionName('id-name', 'http://domain.com');
});
ETA: "body" was supposed to be an iframe (oops), so am not using window.load.
First of all, the syntax of your jQuery is wrong. The jQuery that's analogous would be:
$('#id-name').load(function() {
functionName('id-name', "http://domain.com');
});
To bind an event handler, you have to supply a function, you were actually calling the function at the binding time.
However, this is not equivalent for a few reasons.
First, you're binding the handler to the #id-name element, not the body (unles you also did <body id="id-name">. So it wouldn't run when the body is loaded, but only when that specific element is loaded. In general, per-element load handlers are only useful for elements that have separate sources that get loaded asynchronously (e.g. images and iframes); they allow you to detect and take action when those elements are filled in. This is particular useful if you're changing the source dynamically.
Second, ssuming your jQuery code is in the $(document).ready(...) handler, as most jQuery code is, it doesn't run until after the DOM is fully loaded. By that time, the body's onload event has already been triggered. Any handlers added at this time will not run for elements that were already loaded. I've created a fiddle that demonstrates this:
<body onload="alert('inline body onload');">
<div id="foo"></div>
</body>
$(document).ready(function () {
$("#foo").load(function () {
alert("foo onload");
});
$("body").load(function () {
alert("jquery body onload");
});
});
Only the inline body onload alert fires.
However, if you just want a jQuery equivalent to putting a function call in the <body onload=""> attribute, the $(document).ready() handler is considered analogous. See jQuery equivalent of body onLoad, the first question in the Related sidebar.
However, as Gloserio's answer says, $(window).load(...) does work, despite the timing (it's recognized specially, similar to $(document).ready()). This modified fiddle demonstrates it.
$(window).load(function () {
functionName('id-name', "http://domain.com');
});
Seems to be a fair enough equivalent of body's load event.
Related :
load event in jQuery
SOF has answered all : jQuery equivalent of body onLoad
onload is a DOM event that is triggered when the page begins to load.
.load() is a shortcut to an AJAX call using jQuery.
They really have nothing in common...other than having "load" in their names.
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 .
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.
I have a problem that happens only on a specific computer(FFX 3.6.13,Windows 7,jQuery 1.4.3).
Sometimes document.ready is fired but when trying to get elements to attach the event handlers,the elements don't exist!
the code goes something like this:
$(function(){
window.initStart = true;
$("#id_of_element").click(function()...);
window.initEnd = $("#id_of_element");
});
the window.initStart/End are there for debugging,sometimes this code runs just fine,but sometimes window.initEnd is just a empty jQuery set(length == 0).
What this means is that document.ready is always fired,but sometimes it is fired before elements are available.
Does anybody had this problem? what could the problem be?
One way that you could try to get around this would be with using .live instead of .click. The following code
$('#idOfDiv').live('click', function() { doStuff(); });
will attach the input function to the click event of everything that is dropped on the page with an id of 'idOfDiv' as soon as it makes it to the page. Whereas .click executes immediately, this should be attached no matter what time the divs make it to the page.
Cheers
There's an article on SitePoint that demonstrates how to sense when certain dom elements are available.
Also I know this is a version specific issue, but if you were on Jquery 1.5 the deferred objects stuff would be useful here.
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.
});