What event does JQuery $function() fire on? - javascript

We have a JQuery $(function() statement as:
<script type="text/javascript">
$(function(){
//Code..
})
</script>
Dumb question - when exactly is this function executed? Is it when the entire HTML page has been downloaded by the client?
What is benefit of using the wrapping your code within $(function() as opposed to just doing:
<script type="text/javascript">
//Code..
</script>

It fires when the document has been parsed and is ready, and is the equivalent of $(document).ready(function () { }).
The obvious benefit is that having your script tag before other elements on the page means that your script can interact with them even though they're not available at parse time. If you run your script before elements have been parsed and the document is not ready, they will not be available for interaction.

It is executed as soon as the DOM is parsed and is invoked in order of appearance if there are multiple appearances. At this point the document is however not displayed, its just parsed.

When the document completes loading. It is the same as writing this:
$(document).ready(function(){});
EDIT: To answer your second question:
If you don't wrap your code in the block above then it would fire as soon as it is encountered instead of after all the controls on the page have loaded. So if a block was at the top of a page and it referred to elements in the page those references would not work as the elements have not loaded yet.
But if you wrap in the block then you know that the page has loaded and all elements are available to now reference.

It fires after the the document has fully loaded, the DOM tree has been initialized, all CSS styles have been applied and all Javascript has been executed. It differs from the load event in that elements (other than CSS/JS) that load their content from other URLs, such as images or flash files, have not necessarily finished loading at this point. This is usually called the "domready" or "domloaded" event, and some modern browsers support it directly (e.g. Firefox has a DomContentLoaded event), and on others it can be simulated with various tricks, like using the defer attribute or placing a script at the very end of the body.
The advantage is that you can reliably interact with the document at this time; for example you can set an event handler on an element with a certain ID and be sure that it already exists in the DOM tree. On the other hand, it can run considerably earlier than the load event, if some external resource is slow to load. If your script is at the end of your HTML code, then there might be little difference in using or not using the domready event, but usually scripts are called from the head tag, and at that point no elements of the body are available yet.

Related

When to use "window.onload"?

In JavaScript, when I want to run a script once when the page has loaded, should I use window.onload or just write the script?
For example, if I want to have a pop-up, should I write (directly inside the <script> tag):
alert("hello!");
Or:
window.onload = function() {
alert("hello!");
}
Both appear to run just after the page is loaded. What is the the difference?
The other answers all seem out of date
First off, putting scripts at the top and using window.onload is an anti-pattern. It's left over from IE days at best or mis-understandings of JavaScript and the browser at worst.
You can just move your scripts the the bottom of your html
<html>
<head>
<title>My Page</title>
</head>
<body>
content
<script src="some-external.js"></script>
<script>
some in page code
</script>
</body>
</html>
The only reason people used window.onload is because they mistakenly believed scripts needed to go in the head section. Because things are executed in order if your script was in the head section then the body and your content didn't yet exist by definition of execute in order.
The hacky workaround was to use window.onload to wait for the rest of the page to load. Moving your script to the bottom also solved that issue and now there's no need to use window.onload since your body and content will have already been loaded.
The more modern solution is to use the defer tag on your scripts but to use that your scripts need to all be external.
<head>
<script src="some-external.js" defer></script>
<script src="some-other-external.js" defer></script>
</head>
This has the advantage that the browser will start downloading the scripts immediately and it will execute them in the order specified but it will wait to execute them until after the page has loaded, no need for window.onload or the better but still unneeded window.addEventListener('load', ...
window.onload just runs when the browser gets to it.
window.addEventListener waits for the window to be loaded before running it.
In general you should do the second, but you should attach an event listener to it instead of defining the function. For example:
window.addEventListener('load',
function() {
alert('hello!');
}, false);
Here's the documentation on MDN.
According to it:
The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images and sub-frames have finished loading.
Your first snippet of code will run as soon as browser hit this spot in HTML.
The second snippet will trigger popup when the DOM and all images are fully loaded (see the specs).
Considering the alert() function, it doesn't really matter at which point it will run (it doesn't depend on anything besides window object). But if you want to manipulate the DOM - you should definitely wait for it to properly load.
That depends on if you want it to run when the script element is encountered or if you want it to run when the load event fires (which is after the entire document (including such things as images) has loaded).
Neither is always right.
In general, however, I'd avoid assigning functions directly to onload in favour of using addEventListener (with compatibility libraries if I needed to support older browsers).
The reason for waiting for the DOM to be loaded is so that you can target any elements that load after your script. If you're just creating an alert, it doesn't matter. Let's say, however, you were targeting a div that was in your markup after your script, you would get an error if you don't wait until that piece of the DOM tree to load.
document.ready is a great alternative to window.onload if you're using jQuery.
See here: window.onload vs $(document).ready()
You have three alternatives:
Directly inside the script tag runs it as soon as it is parsed.
Inside document.addEventListener( "DOMContentLoaded", function(){}); will run it once the DOM is ready.
Inside window.onload function(){}) will run as soon as all page resources are loaded.

Javascript: accessing DOM before document.onload

I have a page which has document.body.onload=function(){...} but this is suffering delays because the document also contains external <img> tags etc; onload seems to be only getting fired after these external sites have delivered some kind of response.
I put the code in onload because I thought the DOM tree wasn't fully available until then (e.g. document.getElementById(x) might return null if it is called too soon).
Is there an event which triggers after everything in the DOM is accessible, but before everything has been loaded?
You can just place your <script> tag at the end of the body since the html is parsed in sequence.
Additionally, you could look at jquery's document.ready. Even if you don't want to use jquery, you can have a look at how they handle it. ready does exactly what you're asking for.
Sure you can:
Maybe you have two options:
1)
by using jQuery:
with $(document).ready(), you can get your events to load or fire or whatever you want them to do before the window loads.
2)
DOMContentLoaded
Reference: https://developer.mozilla.org/en/DOM/DOM_event_reference/DOMContentLoaded
function checkDom(yourFunc)
{
window.addEventListener('DOMContentLoaded', yourFunc);
}
You should consider if you really need the whole document loaded. As long as your libraries are already loaded and the DOM nodes you are interested in are on the page, you can act immediately. This sort of code makes a page "come alive" much faster than one that waits for every last resource to load:
<form name="foo">
<!-- ... -->
</form>
<script>
var form = new My.FormWidget(document.forms.foo);
</script>
This has the added benefit of forcing you to encapsulate logic in the FormWidget (you should want to keep an "inline" script like that as brief as possible).

what is the best way to make sure javascript is running when page is fully loaded?

I am trying to run my javascript in my asp.net webform page but I am not sure it runs properly because all the elements are not loaded yet. How can I make sure my script is at the very bottom of the page with using jquery? So it can run when the page is loaded?
Even though everyone says use $(document).ready it's kind of an anti-pattern.
What you really want to do is put any scripts you want to load at the end of the body
<html>
<head> ... </head>
<body>
...
<script src="..." ></script>
</html>
As long as your scripts are at the end of all your other HTML content the javascript will only fire when the content above it has loaded.
With pure JavaScript, you can use
window.onload = function() {
// Page loaded
};
Or you can use jQuery's ready function:
$( document ).ready( function() {
// Dom loaded
} );
Note: jQuery's ready function fires when the DOM has loaded (unless the browser does not support a dom-ready method), not when the whole page has loaded (images, scripts, etc).
Use .ready():
$(document).ready(function($) {
// page is loaded
});
While JavaScript provides the load event for executing code when a
page is rendered, this event does not get triggered until all assets
such as images have been completely received. In most cases, the
script can be run as soon as the DOM hierarchy has been fully
constructed. 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. When using
scripts that rely on the value of CSS style properties, it's important
to reference external stylesheets or embed style elements before
referencing the scripts.
With jQuery, you want to attach to the ready event. This gets fired when all DOM elements have been loaded:
jQuery(document).ready(function(){
// jQuery Code here
});
Shorthand version:
$(function(){
// ...
});
Using this method, I usually put my jQuery in an external file, or in the <head> tag.
You should put your code inside the document ready block as suggested in the JQuery documentation.
This way it will be loaded when all the scripts will be loaded.
$(document).ready(function(){
//Put your code here
});
What is the best way to make sure javascript is running when page is fully loaded?
If you mean "fully loaded" literally, i.e., all images and other resources downloaded, then you have to use an onload handler, e.g.:
window.onload = function() {
// Everything has loaded, so put your code here
};
If you mean "after all of the HTML has been parsed and all elements are accessible from script", at which point images may still be downloading, then you can either put your script at the bottom of the source HTML or use a document.ready handler. Or both. Refer to any of the other answers for details.

What to use in place of $(document).ready();?

So I'm using jquery along with some plugins I wrote.
I do all the initialization in a $(document).ready(function(){}) block however this is executed when the whole DOM has been loaded and is ready to be used.
However that would take long eg. when there is a server load. Or maybe the user clicks a button that has been loaded while the rest of the page hasn't loaded yet (and thus document.ready() hasn't been executed yet) in which case it would do nothing.
So, what if I want a code to be executed right after the related part of the page has been loaded instead of waiting for the WHOLE page to be loaded?
I know placing inline code right after the html that this js operates on would do the trick but what if that code uses a library like jQuery that hasn't been loaded yet?
I know placing inline code right after the html that this js operates on would do the trick but what if that code uses a library like jQuery that hasn't been loaded yet?
That would be the only way. The HTML is parsed from top to bottom. So you can expect every script you included to be accesible after you included it.
Your page should still work without JavaScript anyway, so a user clicking a button extremely fast will just temporarily have a somewhat degraded experience.
That being said, the DOM is basically ready when the HTML document all scripts are loaded. Since you cannot execute meaningful JavaScript before the JavaScript code is loaded (duh), I'd have a close look at page performance. Sending an HTML document and 2,3 JavaScript files should not be slow.
You could also use the old-style inline event handlers, like <button onclick="registerButtonClickEvent()">. However, this would introduce a complex, potentially buggy and hardly testable layer of temporary event holding.
If your <script src="jquery-whatever.js> line precedes the first clickable element in your HTML, it is guaranteed that the jquery library will be loaded and run before the user has anything useful to click on.
Just don't add async or defer attributes to the script element.
The onload event isn't triggered from all html elements, so you're forced to wait for window load. It doesn't matter where you load jQuery since it will have to wait for document to be ready. That total time required to load jQuery plus the rest of the document will be thet same.

Where is the best place to place a Javascript snippet to alter the DOM of a page before it renders

I have a few dynamic pages and I want to alter certain elements before the page has fully rendered.
My snippet is something like:
document.body.getElementById("change").innerHTML = "<img src...";
I do not have access to change the content server side.
Where is the best place to put the snippet to have the code run before the page it has rendered?
Rather, is putting the Javascript in either the HEAD (inside the window.onload event?) or before the closing BODY (not inside an event listener) optimal?
I'm afraid you are highly unlikely to be able to execute your script before the page renders. Sure you can place an inline script and have it use document.write(...) at the place you'd like it to display your content, but this is a horrible solution. Orherwise the best you can do is at the 'DOM Ready' event, although it's difficult to do on all browsers consistently, you really need a library to abstract the details. jQuery provides it's ready method to fire an event when the DOM is ready, rather than when the page and all resources are finished loading.
Since the browser usually renders elements immediately after they have been parsed the best way would be do place the code in a script element directly after the referenced element:
<div id="change"></div>
<script type="text/javascript">
document.body.getElementById("change").innerHTML = "<img src...";
</script>
Not sure I understand your problem correctly, but if you use an event listener inside the head (such as jQuery's $(document).ready()), you will be able to alter the element once the dom structure has been loaded by passing your snippet to the function (handler) being called when the event fires.
<HEAD>
//...
<SCRIPT type="text/javascript">
$(document).ready(function() {
$("#change").append(
$("<img src=\"...\">")
) ;
}) ;
<SCRIPT>
</HEAD>
Using core javascript you will have to fork your event listeners for mozilla (W3C) and internet explorer event specifications. There's loads of documentation on how to do that on the internet.
Either way the best thing to do in this case obviously would be to create the content yourself, not altering it post rendering.
AFAIK you cannot do this. Because before a page is rendered there won't be any element and you can't access elements that haven't been loaded to the DOM tree.
If you do not want to render any elements before you make the DOM changes, you could set CSS display: none on the body element and then change it to display: block once you're done.

Categories

Resources