document.readystate = undefined - javascript

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.

Related

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

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.

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).

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.

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 event does JQuery $function() fire on?

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.

Categories

Resources