jQuery onLoad x jQuery onDomready - javascript

Every time I use jsFiddle I see two options to initialize the contents via jQuery: onLoad or onDomReady.
I Tested with most of the scripts I wrote and there was no functional difference. Searching on Google I saw that one of the main differences is that via onLoad, scripts will only start running after all the elements are loaded and that includes CSS external files, JS external files, images and etc., which can be useful if you need to load JS files in a certain order, but at any given moment one of these files makes reference to another who has not been loaded yet, while via onDomReady once the HTML page content is loaded, scripts begin to be loaded already without necessarily others have been.
Got this difference right? Is there any other differences to be studied and perceived?

Making comment as answer:
One major difference, jquery ready 'pseudo' event will be fired even handler
is set after DOM is effectively 'ready', jquery using internally a
promise. Window onload event won't be fired if handler is set after
window is loaded. e.g: http://jsfiddle.net/c58a6/
It should be then noted that there is no in-build equivalent of jQuery document ready event. For example, DOMContentLoaded in-build event won't be fired if settled after the DOM is ready.

Related

Whic spec define the ready event?

First at all, I want know the difference between the $(document).ready and the $(window).load, then I know this.
But, I have some new questions.what is the ready event, what is the detail. what is the load event.
I have find the description of load event in the HTML spec.
But I can't find the description of the ready event.
ready() is an abstraction implemented by jQuery based on DOMContentLoaded.
load() (Note this jQuery method is depreciated) is based on window.onload.
The MDN articles link to the specification.
In JavaScript window is one of core object and defines several useful events e.g. onload, before jQuery comes, if want to execute any code, once DOM is loaded completely, we use window.onload event
There is a problem with window.onload , it not exactly executed when DOM is loaded but it executes after all content including big images are loaded completely. Browser normally delay executing onload code, until all page content is loaded, because of this user can see significant delay between they first see the page and the time that code inside onload get executed, this delay is particularly notable, if your page content heavy images, flash videos or other heavy content with low bandwidth internet connection.
jQuery solves this problem by introducing ready event, you might have seen code like below in several JavaScript files or HTML pages :
$(document).ready(function(){
alert("Inside jQuery ready method");
});
here $() is a shortcut for jQuery() function, and we wrap document object into jQuery object to use ready() method. We are passing an anonymous function to ready() method, which will be executed once DOM is loaded. It doesn't wait till all DOM content available e.g. images. By the way, instead of using $(document).ready() function, you can also use following short-cut, which has same effect :
$(function() {
alert("shortcut for document.ready method in jQuery");
});
Apart from faster execution, one of the key advantage of jQuery ready method over JavaScript window onload event is that, you can use them multiple times in your page, unlike onload event, which can only be bind to a single function. Browser will ensure to execute all document.ready code to execute in the order, they are specified in the HTML page.
Hope this will be useful for you.
Thanks

Detect async script load in Chrome

I'm writing a chrome extension that needs to examine elements in the DOM. I'm currently trying to solve cases where scripts are added to the DOM after document.onload has fired, and those scripts add more elements to the DOM, and I want to look at those elements. Sometimes the elements are in a subframe, and sometimes the script adds them with document.write. Yeah, I know, I know.
The main issue currently seems to be that I can't detect whether a script has loaded already. If it hasn't loaded, I can safely attach a listener to script.onload, but if it has already loaded, onload will not fire.
In several other spots I do things like check readyState to see if a document is already ready. If it is, I execute my code, and if it is not, I attach an onload listener. However, async scripts in Chrome do not seem to have a readyState despite references to such a property in several SO answers.
So is there any way to figure out if an async script is already loaded? Since this is Chrome-specific, it doesn't need to be cross-browser compatible. Is there some way to use MutationObserver to reliably attach an onload listener for every script and track its state manually?
Thanks!
To detect the scripts which are loaded on the DOM, retrieve all the script tags:
document.querySelectorAll('script');
This returns an array of scripts loaded on the DOM. Calling .length on the array will show you how many scripts are loaded. And you can reference these scripts via their .src or other attributes to do things like getting their child or sibling elements.

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 :)!

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.

difference between pageLoad , onload & $(document).ready()

i need to know in more detail of what is the differences between pageLoad , onload & $(document).ready()
I found answer but that is not ver clear to me.
the answer is like
The ready event occurs after the HTML document has been loaded, while the onload event occurs later, when all content (e.g. images) also has been loaded.
The onload event is a standard event in the DOM, while the ready event is specific to jQuery. The purpose of the ready event is that it should occur as early as possible after the document has loaded, so that code that adds funcionality to the elements in the page doesn't have to wait for all content to load.
the person trying to say ready event occurs after the HTML document has been loaded
and onload event occur after all page element like image etc being loaded.
So what is HTML document load? I know HTML document load means all page element load complete.
What does mean like dom is ready or loaded? What is the difference between HTML document load & dom load?
Please make me understand with example.
Thanks
I don't know what you mean by pageLoad, but here's some info on onload and $(document).ready().
window.onload fires when everything in the page has finished loading. That means that not only the entire DOM is loaded, but any linked resources such as images are fully loaded. Because this waits for images to finish loading, it can sometimes take a long time to fire window.onload. Unless you really need to wait until images are finished loading, you do not generally want to wait this long to start running your javascript that modifies the page or hooks up event handlers, etc...
$(document).ready() is a jQuery-specific event that fires as soon as the DOM is ready for manipulation, but potentially long before images have finished loading. This occurs after all objects present in the page HTML have been parsed and initialized by the browser and after all scripts in the page have been loaded. At the moment of this event, it is safe to modify the DOM in all browsers. This even may occur a little earlier or later in some browsers as the mechanism for detecting when the DOM is safely loaded varies between older and newer browsers.
The jQuery 1.6.x implementation for $(document).ready() uses a number of different detection mechanisms for when the DOM is ready. The preferred method is when the DOMContentLoaded event triggers on the document object. But, this event is only supported by some browsers so it has fallback mechanisms for other browsers.
Both of these events will fire only once per page.
Let's draw an analogy to compare the process of loading a web page to a chef with a recipe:
First, the chef (browser) reads the entire recipe (downloads the HTML document), to make sure that he understands the steps (HTML code) and that he knows what ingredients (images), utensils (style sheets), and appliances (external scripts) he will need to have in his kitchen (browser cache).
As the chef continues reading, he sends his assistant to the pantry to get the ingredients, utensils, and appliances (download the other files from the server). When he is finished reading the recipe ($(document).ready()), he starts to follow the steps (display the page), but sometimes he gets to a step before his assistant returns with the necessary materials to complete that step. He's pretty skilled, though, so he's still able to complete the later steps while he waits. (The analogy breaks down just a bit here, but basically: the browser lays out the page as well as it can based on the HTML; when you see a page load and then the fonts or layout change after a couple of seconds because it finally got the style sheet... just imagine that this chef is somehow able to add eggs to a cake that's already in the oven.)
It's only after the chef's assistant has brought everything identified in the recipe back to the kitchen (the browser has loaded all of the content) that the chef can put the completed meal onto the plate and garnish it (run the onload event code).
The onload event is a standard event in the DOM, while the ready event is specific to jQuery.
The DOM is the Document Object Model, a basic component of ordinary JavaScript. This means that all modern web browsers already know what onload means.
jQuery is a widely-used JavaScript library. In order for your script to properly use $(document).ready(), you will have to link to a copy of the jQuery library. Browsers don't know what $(document).ready() means without jQuery.

Categories