JavaScript function after page load and other JS/Ajax function completion [duplicate] - javascript

I was using $(window).load(function(){}); for my projects until somewhere I saw that somebody said we could just use $(function(){}); and they would perform identically.
But now that I have more experience I have noticed that they are not identical. I noticed that the first piece kicks in a little bit after the second piece of code.
I just want to know what's the difference?

$(document).ready(function(){})
will wait till the document is loaded(DOM tree is loaded) and not till the entire window is loaded. for example It will not wait for the images,css or javascript to be fully loaded . Once the DOM is loaded with all the HTML components and event handlers the document is ready to be processed and then the $(document).ready() will complete
$(window).load(function(){});
This waits for the entire window to be loaded. When the entire page is loaded then only the $(window).load() is completed. Hence obviously $(document).ready(function(){}) finishes before $(window).load() because populating the components(like images,css) takes more time then just loading the DOM tree.
So $(function(){}); cannot be used as a replacement for $(window).load(function(){});

From the jQuery docs itself.
The first thing that most Javascript programmers end up doing is adding some code to their program, similar to this:
window.onload = function(){ alert("welcome"); }
Inside of which is the code that you want to run right when the page is loaded. Problematically, however, the Javascript code isn't run until all images are finished downloading (this includes banner ads). The reason for using window.onload in the first place is that the HTML 'document' isn't finished loading yet, when you first try to run your code.
To circumvent both problems, jQuery has a simple statement that checks the document and waits until it's ready to be manipulated, known as the ready event:
$(document).ready(function(){
// Your code here
});
Now,
$(window).load(function(){}); is equal to window.onload = function(){ alert("welcome"); }
And, $(function(){}); is a shortcut to $(document).ready(function(){ });
I think , this clears everything :)

$(window).load from my experience waits until everything including images is loaded before running where as $(function() {}); has the same behaviour as $(document).ready(function() {});
Please someone correct me if I am wrong.

The second is/was a shortcut for $(document).ready(), which should run before window's load event.
Note that $(document).ready() is the preferred way of binding something to document load; there are a couple other ways of doing it like the one you showed, but that's preferred.

Related

What is the advantage of using jquery on ready instead call function

What is the advantage of using $(document).ready(my_function) instead call my_function() in the bottom of my html script?
They both do the same thing.
$(document).ready(function() { // code }); allows you to run the javascript once the page onload function has been called. This is the same as running it once the DOM has loaded by calling it at the end of your HTML.
Only if you put the function at the very bottom of the page, there is no advantage. However, you usually want to have the choice to put code where you like it. $(document).ready() gives you this choice (actually the underlying javascript does).
Furthermore, for other programmers, it might not seem obvious that this function has to be executed right away when the page loads, and might therefor refactor the function somewhere else unknowingly. By using the document ready event, you're making your code more explicit i.e. saying "this piece of code needs to run as soon as the document has been loaded".

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.

Difference between Javascript onload event and plain script in the html page

What is the difference between these two pieces of code:
Sample 1:
<script type="text/javascript">
function myfunc () {
alert('hi');
}
window.onload = myfunc;
</script>
Sample 2:
<script type="text/javascript">
alert('hi');//no function used
</script>
Both pieces of code execute successfully.
The window.onload makes it so that all DOM elements are loaded before the script runs - that is, if your script modifies or uses DOM elements, then it should be attached to window.onload (or something equivalent in a framework). If it is independent of the DOM you can use either. Refer to the Mozilla Developer Network page for more information. Note that inlined scripts that don't run from window.onload can run once the parser reaches it - it doesn't wait for the rest of the DOM to be loaded.
The first executes after the page completes loading, the other as soon as it is parsed
If you want to see a difference duplicate both code snippets (copy paste twice) and see how they behave
Sample 1 and Sample 2 do the same thing. However, window.onload in Sample 1 executes the function when the HTML content (and all images, stylesheets and remote scripts) are fully loaded (not when all the DOM elements are loaded).
Sample 2 does the same as Sample 1 but executes the script instantly. You will see the difference when you have a page that takes a while to fully load. Your test page might have been basic so that it seemed that they execute at the same time (when in fact window.onload executed after sample 2).
window.onload is normally used when you need to execute Javascript code after the page loaded. The inline script in sample two can be used if you want Javascript to execute INSTANTLY after a particular DOM Element has been loaded in the browser for example.
onload event triggers when the page has loaded completely including images, audio, etc.
But directly writing a statement will execute instantaneously.
Hence, onload alert will trigger after the other one.
Check this DEMO
Another important difference is that , since the second script executes immediately , You won't be able to access any DOM elements which comes after that script.
For example if you have a DIV element just before the ending of the tag , you cannot use document.getElementById ( or similar DOM accessing function ) to get that particular DIV.
But with the first script, which will be executed only after the page load , You can access any element in the DOM

Run JavaScript function when the DOM is "ready"?

I'm using a JavaScript upload script that says to run the initialize function as soon as the DOM is ready. I currently have it working just fine with either a call to the function with body.onload or directly after the function is defined. The function builds some HTML in a placeholder div that acts as the file uploader tool.
My question is what is the best practice here? Since it works for now, why would the instructions say to run the init function as soon as the DOM is ready? Should I be adding a <script> tag directly after the placeholder DIV for example?
<script>
window.addEventListener("DOMContentLoaded", function() {
// do stuff
}, false);
</script>
You do that so you know all the parsed elements are available in the DOM etc.
The easiest solution is using jQuery and its $(document).ready(function() { .... }); function. Instead of .... you put your own code.
Note that it basically does the same thing #Shadow2531 suggested, but also works in old browsers not supporting that event.
The DOM is usually ready before onLoad runs. onLoad only runs after everything loads - external scripts, images, stylesheets, etc.
But the DOM, i.e. the HTML structure is ready before that. If you run the code at the bottom of the page (or after the parts of the page the script works with) that will work fine as well.
In 2015 you have two options with modern browsers:
document.onload
this fires when the document is loaded, but other resources (most notably images) have not necessarily finished loading.
window.onload
this fires when the document is loaded, AND all other resources (again, most notably images) are loaded.
Both of the above events would be better utilized with window.addEventListener() of course, as multiple listeners would be allowed.
You could also just move the <script> to the bottom of your page like this:
<html>
<body>
<main></main>
<script>
// code
</script>
</body>
</html>
As you probably know you should not run init functions before the DOM is fully loaded.
The reason you must run the init function as soon as the DOM is ready, is that once the page has loaded the user starts hitting buttons etc. You have to minimize the small inavoidable gap where the page is loaded and the init-functions haven't run yet. If this gap gets too big (ie. too long time) your user might experience inappropiate behaviour... (ie. your upload will not work).
Other users have provided fine examples of how to call the init function, so I will not repeat it here... ;)
Get jQuery and use the following code.
$(document).ready(function(){
// Do stuff
});
var Tette =
{
init: function()
{
/* Your HTML code */
}
};
Core.start(Tette);
You can try in this code, registering "Core.start(your object)" on the last line of the script. This is a way to load in safety your functions after the DOM loading.

document.readystate = undefined

From external JS script I use document.readystate to determine whether the document is loaded.
If its not loaded I attach Onload event listner.
However when I run the script from IEPRO (similar to FF greasemonkey) on IE7 document.readystate returns 'undefined'. (I guess that IE7PRO runs the script after the document has loaded already).
How can I tell if the document is loaded or not in other ways that will work across browsers?
Clarifications (following first two answers):
1.My question is not how to perform onload attaching. My question is how to determine whether the document (or DOM) has already loaded in other means than document.readystate
I cant change the document. my script is an addon to random pages I have no control of.
The only cross-browser way of doing this, that I know of, is to attach a function to the load event of window; this script should probably go in the head. When this fires, set a boolean so that you know everything is loaded later.
The Prototype library does this; see function fireContentLoadedEvent() in the source.
I am not sure of your whole conclusion but sounds like you can just use jquery and set up your code like this:
<script language="javascript" type="text/javascript">
$(document).ready(function(){
//have all your code of what you are trying to do here
//
//
});
</script>
The help site for IEPRO UserScripts seems to indicate they run after the page is loaded. So why do you need to check if the page is loaded?
You can do this in body.onload:
<body onload="document.ready=true;">...
This JavaScript will be executed after the document has been loaded. Just wait until document.ready is true (or no longer underfined).
The better way is to call a JS function in onload which then invokes your external script. This doesn't involve busy waiting but might not work in your case. If you load the external document in a frame, you can store the function to call in the parent document and use "window.parent.function()" from the nested document.

Categories

Resources