What is the difference between $(window).load and $(document).ready? - javascript

I have been having a problem lately with my JavaScript CODE and taking a portion of my code out of my $(document).ready() and putting it within $(window).load() fixed the problem.
Now I understand that window.load is fired just after document.ready, but why is it not ready after document.ready, that is after window.load()?

load is called when all assets are done loading, including images. ready is fired when the DOM is ready for interaction.
From the MDC, window.onload:
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.
From the jQuery API documentation, .ready( handler ):
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.

$(document).ready() means that the DOM of your page is ready to be manipulated.
window.load() is triggered when the whole page (incl. components like CSS and image files) has been completely loaded.
What are you trying to achieve?

$(document).ready(function(){
//code here
});
The code above is used almost every time when we work with jQuery.
This code is used when we want to initialize our jQuery codes after the DOM is ready.
$(window).load()
Sometimes you want to manipulate pictures. For example you want to vertically and horizontally align a picture and you need to get the width and height of the picture in order to do that. With $(document).ready() you won’t be able to do that if the visitor doesn’t have the image already loaded, in which case you need to initialize the jquery alignment function when the image finishes loading. That’s where we use $(window).load()

$(document).ready is jQuery event that is fired when DOM is loaded, so it’s fired when the document structure is ready.
$(window).load event is fired after whole content (including css, images etc..) is loaded.
This is major difference.

$(document).ready() is wrap DOM in <body>...</body>
$(window).load() is papa of document wrap all DOM in <html>...</html>
Let's use in your case to save render processing.

In simple words, window.load is called when all content of window is loaded whereas document.ready is called when DOM is loaded and document structure is ready.

Load state is the state when the window object has been created and all necessary components including DOM has been loaded in memory, but has not been passed to the rendering engine for rendering the same in page.
Ready state on the other hand makes it sure that the DOM elements, events and other dependent components are passed on to the rendering engine, rendered on page, and is ready for interaction and manipulation.

$(document).ready is slider fast in comparison $(window).load Event.
$(document).ready is fire when Dom is load but $(window).load Event
fire when Dom ,css and images fully loaded.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="https://code.jquery.com/jquery-1.12.4.js" ></script>
<script>
$(window).load(function () {
var img = $('#img1');
alert( "Image Height = " + img.height() + "<br>Image Width = " + img.width());
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<img id="img1" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTozkxoNSH8739juRXJJX5JxREAB6I30bFyexPoCdRVa2fKfH2d" />
</div>
</form>
</body>
</html>

$(document).ready is a jQuery event. It fires as soon as the DOM is loaded and ready to be manipulated by script. This is the earliest point in the page load process where the script can safely access elements in the page's html DOM. This event is fired before all the images, css etc. are fully loaded.
window.load() is triggered when the whole page (incl. components like CSS and image files) has been completely loaded.

Related

Best way to call a JavaScript script after the HTML body loads with no JQuery?

I have a somewhat large .js file that is currently called in the header of a HTML page, but it fails to execute because the elements have not loaded when the script is called. What is the best way to implement this? I've tried adding
document.addEventListener("DOMContentLoaded", load, false);
to the script but that doesn't seem to work. Calling the script in the footer or inline is not an option, nor is JQuery.
Meet onload.
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, scripts, links and sub-frames have finished loading.
There are also Gecko-Specific DOM Events like DOMContentLoaded and
DOMFrameContentLoaded (which can be handled using
EventTarget.addEventListener()) which are fired after the DOM for the
page has been constructed, but do not wait for other resources to
finish loading.

Javascript: How to add an event listener to the body of a CMS, with the JS code in the header

I wrote a script that adds a listener to a for an onClick event. When clicked, it searches the document for any element with a specific class "someclass", and then performs some operations on it etc..
The problem is, after finding all the elements with class="someclass", the array of all the elements with class="someclass" is null. I think this is because the JS code that adds the listener is in the header, and when it runs, the body (that comes from a different php file from the CMS) that contains the actual has no yet loaded.
What do I do about this?
A side note, I am trying to do this using pure JS. I do not want to have anything other than one single external .js file. So that means no jquery or other API's, and no editing the html.
What are my options here? Thank you for reading.
Ideally you should move your JS right before the closing body tag. If that's not possible, you need to either use the DOMContentLoaded event of the document object or the load event of the window object.
Your problem is that the DOM of your page isn't ready so your JS code doesn't have anything to access yet. More info here:
https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded
https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers.onload
DOMContentLoaded (works in modern Browsers and IE9+):
document.addEventListener('DOMContentLoaded', function(event) {
console.log('DOM fully loaded and parsed');
});
Load (works in all Browsers):
window.onload = function() {
console.log('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, scripts, links and sub-frames have finished loading.');
};

What is the order in which various load functions/methods execute [duplicate]

This question already has answers here:
jQuery - What are differences between $(document).ready and $(window).load?
(8 answers)
Closed 8 years ago.
$(document).ready(), $(window).load(function(), <body onload="load()">, data-ng-init="init()", $(function(){...});
There are probably about ten other "load" functions between jQuery, Angular, and old-fashioned JavaScript; I cannot find a definitive resource which states in which order these various methods actually fire (across diverse browsers might be another consideration). How many more are there? What are they called? In what order do they do their magic?
I can answer for jQuery. If you're talking about the document loading, there are two main points in time that you can get notified:
When the DOM has been parsed and is now safe for manipulation (but some resources in the page may not have yet finished loading like images).
When all resources specifically declared in the HTML file have been loaded (like images, but not iframes). There are multiple ways of registering a notification for each of these two events.
For event #2, these two events are triggered at the same time when all resources statically declared in the HTML file (scripts, style sheets, images, etc...) have finished loading (not including iframe content).
$(window).load(function()
<body onload="load()">
These next two are also the same but just different ways of declaring the same event and in modern browsers these are triggered by the DOMContentLoaded event which occurs before the above event and is described by MDN as below:
$(document).ready()
$(function(){...});
DOMContentLoaded is described by MDN:
The DOMContentLoaded event is fired when the document has been
completely loaded and parsed, without waiting for stylesheets, images,
and subframes to finish loading (the load event can be used to detect
a fully-loaded page).
FYI, in older browsers that do not generate the DOMContentLoaded event, these functions will be called on a onreadystatechange notification when document.readyState === "complete" and in a really old browser, it might not be triggered until window.onload occurs.
If you look into the browser internals, the browser keeps a document.readyState variable. It has possible values of "loading", "interactive" and "complete".
"loading" was meant to mean that it is in the process of loading the page.
"interactive" was meant to mean that the HTML has been parsed, but some sub-resources (other than images) are still loading (perhaps style sheets or scripts)
"complete" means that the document has finished loading (except for images and iframes)
So, it would have been possible to expose these other load events in jQuery. But (and this is the big but), the ONLY state that works consistently across all browsers is the "complete" state. "interactive" was probably meant to be the point at which you had a completely parsed DOM and you could start changing the DOM even if things like stylesheets weren't yet loaded, but it turned out to be too bug-ridden in IE for it to be worth even trying to use it as the history of jQuery development shows.
jQuery also has another flavor of .load() which uses ajax to load new content into a given DOM object which has nothing to do with the initial page loading:
$("#content").load("some url", completionFn);
This is called by you and immediately fires an ajax function to retrieve whatever content the URL you give it returns. That content will then be inserted into the DOM element in the jQuery object and when that operation is completed, the completionFn will be called.
And, .load() can also be used to monitor when a specific resource is loaded. This is primarily used with images:
var img = $("<img>");
img.load(function() {
// called when the image finishes loading
});
img.attr("src", "http://example.com/myimage.jpg");
Why Don't you Check it yourself?
Fiddle
As you can see as soon as your DOM becomes ready $(document).ready() is fired and so $(function(){...});. As $(function(){...}); is another way of representing $(document).ready(), It'll not wait for all images and iframes to load.
Also $(window).load(function(), <body OnLoad='function()'> & window.onload = function(){} are same and these event fires when all the content on your page fully loaded including the DOMcontent frames and images. So its kinda slower.
You can Use inline OnLoad for many other elements like img, link, scripts etc.
Like:
<img src="myImage.gif" onload="OnLoadImage()" />
<link rel="stylesheet" type="text/css" href="foo.css" onload="StyleSheetLoaded();" />
<script type="text/javascript" src="https://code.jquery.com/jquery-1.10.1.min.js" Onload="ScriptLoaded();"></script>
onload is supported by the following HTML tags:
<body>, <frame>, <frameset>, <iframe>, <img>, <link>, <script>
And the following Javascript objects:
image, layer, window
Also JavaScript is Browser Dependant and not library Dependant So it'll be constant for all browsers.
Sorry I don't know about the data-ng-init="init()", Which library of JavaScript is it?
Hope it'll Help you. Cheers :)!

jQuery load external JavaScript with $(document).ready fails

I would like to load an external HTML. In addition, the external HTML contains some JavaScript code. Since the load function does not load this script, I have to use getScript:
<div id="external-content"></div>
<script type="text/javascript">
$("#external-content").load("external.html #myid", function() {
// do something
});
$.getScript("external.js");
</script>
That works like a charm unless the external.js has a $(document).ready command, which tries to access elements from external.html. It seems to me, that the event is fired too early. I also tried to put the command $.getScript("external.js"); into the .load callback, but did not succeed. Note that sing external.html separately and including the external.js directly works like expected.
Unfortunately, the timing of this makes sense (ie. this is correct behaviour). The script inside the tag fires up a retrieval of external.html and does not wait for it to return, it keeps moving on to the retrieval of external.js. In the meantime, the 'base' document is still loading and may (in fact probably) will complete before externa.html is retrieved.
So, you can run into a timing situation whereby:
Document is indeed ready (external.html being loaded is not a condition of the DOM being scriptable), external.js is loaded and available, but external.html hasn't been fully loaded yet. The document ready function will fire (because the document IS ready!) before the elements of external.html are present.
If you want to continue this approach, there are probably ways to rejig it such that you are using on() inside external.js to delegate to a listener to the base document (#myid) for events on elements inside external.html.

Popup on complete load of HTML page

Here it is the situation....
I have designed a demo which is made up of HTML in which there are several images and we have made it such a way that it works offline also for ipad using manifest file.
so so once the project/demo is loaded one can use it off line and book mark it so that he can use it any time he wants.
here is the link for reference:
http://iwdfvm2730.wdf.sap.corp:1079/speeddemo/dpr921/
I need help from you guys to show a popup/loader icon when the data or every thing is loaded completely.
thanks,
Kunal
What you gave us looks like an internal corporate address, but unless you dynamically load resources, I'd suggest that you set up an onload handler: <body onload="pageLoaded()">.
You can have a look at the jQuery .load() function. Excerpt from the documentation page on the .ready() function:
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.
So, in essence, the .ready() function executes after loading the DOM, while the .load() function executes after all page assets (including script, CSS and image references) have loaded.

Categories