Difference between onload() and $.ready? - javascript

Can you list the difference between onload() and $(document).ready(function(){..}) functions in the using jQuery?

the load event (a.k.a "onload") on the window and/or body element will fire once all the content of the page has been loaded -- this includes all images, scripts, etc... everything.
In contrast, jquery's $(document).ready(...) function will use a browser-specific mechanism to ensure that your handler is called as soon as possible after the HTML/XML dom is loaded and accessible. This is the earliest point in the page load process where you can safely run script that intends to access elements in the page's html dom. This point arrives earlier (often much earlier) than the final load event, because of the additional time required to load secondary resources (like images, and such).

The main differences between the two are:
Body.Onload() event will be called only after the DOM and associated resources like images got loaded, but jQuery's document.ready() event will be called once the DOM is loaded i.e., it wont wait for the resources like images to get loaded. Hence, the functions in jQuery's ready event will get executed once the HTML structure is loaded without waiting for the resources.
We can have multiple document.ready() in a page but Body.Onload() event cannot.

Document.ready() function triggers as soon as HTML DOM loaded. But the onload() function will trigger after HTML DOM, all the body content like images loaded.

body.onload() cares about both HTML structure and assoicated resources where as document.ready() cares only about the HTML structure.

onload() fires when all the content (everything) on the targeted eleement is fully loaded like CSS, images etc.
$.ready indicates that code in it need to be executed once the targeted elements content loaded and ready to be manipulated by script. It won't wait for the images to load for executing the jQuery script.
.
Ex(body onload):
<body onload="loadBody()">
<script>
function myFunction() {
alert("Page is loaded");
}
</script>
</body
Ex(onload on an element):
<img src="w3html.gif" onload="loadImg()" width="100" height="132">
<script>
function loadImg() {
alert("Image is loaded");
}
</script>
Ex3 ($.ready):
<script type = "text/javascript">
$(document).ready(function() {
alert("$(document).ready fired");
});
</script>

Onload take care about DOM and resources: it checks if images are loaded, script are ready to run and much more.
$.ready simply check if we have read the full DOM of the page.
Please check out this link for more explain and example: http://dailygit.com/difference-between-document-ready-and-window-load-in-jquery/

Related

Copy HTML Table to localStorage

I have a table that is being generated automatically through the javascript application.
See test site here: https://hhpricetools.com/3d-wood-designer/
The summary table is on the last tab or you can click "view summary" at the top to get to it.
The table that is populated based on user choices looks like this:
<table id="summary-table" class="hhpt-summarytable"><tbody>
<tr><td>Style: <b>Side Lofted Barn</b></td>
<td> </td></tr>
<tr><td>Size: <b>10' x 16'</b></td><td> </td></tr>
<tr><td>Siding: <b>LP Smartside - Painted</b></td><td> </td></tr>
<tr><td>Wall Color: <b>Quest Gray #7080</b></td><td> </td></tr>
<tr><td>Trim Color: <b>White</b></td><td> </td></tr>
<tr><td>Roof: <b>Radiant Barrier LP Techshield</b></td><td> </td></tr><tr><td>
</td></tr></tbody></table>
That I am wanting to save to localStorage. For some reason I am getting "undefined" on the actual website above. The jsfiddle works fine, though. Why isn't it doing the same on the website?
var table_copy = $('#summary-table').html();
localStorage.setItem('table',table_copy);
console.log(localStorage.getItem("table"));
https://jsfiddle.net/ebryjz1q/
There are a few methods that you can do to make sure that your JavaScript loads after the DOM/HTML loads.
1. Use defer
You can use defer to load the JavaScript after the HTML has loaded.
To do this, you can simply add the following attribute.
<script defer src="index.js"></script>
This should wait until the DOM has loaded before actually loading the JavaScript.
2. Add <script> to <body>
Another solution is to add the script tag to the end of the body. This will make the JavaScript code load after all of the HTML has loaded.
3. Wait in JavaScript
You can also wait for the DOM to load in JavaScript (without JQuery).
There are two methods.
You can use the DOMContentLoaded event listener. This will wait until the HTML has loaded. However, it won't wait for the images to load, stylesheets, etc.
To use this, you can use addEventListener().
window.addEventListener("DOMContentLoaded", () => {
// Code here will execute only after the DOM has loaded...
});
You can also use the load event, which will load after the HTML has loaded, as well as images, stylesheets, etc.
You can use this listener with addEventListener too.
window.addEventListener("load", () => {
// Code here will execute after everything has loaded...
});
You can do the same thing with the onload event handler property.
window.onload = () => {
// Code here will execute after everything has loaded...
};
In conclusion, there are many ways to make the JavaScript wait until the DOM has loaded.
You need to ensure the DOM has fully loaded before trying to store the HTML.
Try the following:
$('document').ready(function() {
var table_copy = $('#summary-table').html();
localStorage.setItem('table',table_copy);
console.log(localStorage.getItem("table"));
});

getElementById/InnerHTML Function not Working

I'm playing around with Javascript to get back in the swing of things for my second semester web class that recently started, and I've run into an issue getting getElementById and innerHTML to work.
Basically, I want to populate an empty h1 with an Animal name
function favAnimal()
{
document.getElementById("animal").innerHTML="cat"
}
<h1 id="animal" onload="favAnimal()">Favourite Animal Placeholder</h1>
The above does not change anything. If the h1 is empty the result is the same. I've also tried with a <div> to rule out an issue using specific elements.
All help is appreciated and thanks in advance!
An <h1> tag does not have an onload event handler so your function is never being called.
You can use the onload handler for the <body> tag or set up some other event handler to assign your function to.
If you want your code to be triggered when the document is loaded, you can use one of these:
window.addEventListener("load", favAnimal); // all page resources loaded
document.addEventListener("DOMContentLoaded", favAnimal); // HTML done parsing
If you just want your script to be executed right after your <h1> tag has been loaded, you can just place a call to the script right after the tag. The page is parsed/executed in order so that any script will always be able to reference HTML elements that come before it in the document:
<h1 id="animal">Favourite Animal Placeholder</h1>
<script>favAnimal()</script>
Here are some of the things I'm aware of that have a load event:
window
<img>
<body>
<iframe>
<link>
<script>
<embed>
<object>
<video>
<audio>
XMLHttpRequest
And, pretty much any other HTML tag that has a src or href attribute except <a>. The idea is that if the tag is loading some external resource, then there is a load event to know when it is done loading that external resource. If the tag is not loading an external resource, there is probably not a load event for it.
The load event is only dispatched on resources, such as the document, images, ...
If you want to run some script just after an element has been parsed, just add a script element after it:
<script>
function favAnimal() {
document.getElementById("animal").innerHTML = "cat";
}
</script>
<h1 id="animal">Favourite Animal Placeholder</h1>
<script>favAnimal()</script>
What is happening here that ur script file executed earlier than the html renders. So it is not able to locate the element as it is not rendered yet. Browser provides events like onload ,unload. Here u need onload
`Document.addEventListener("DOMContentLoaded",init);
Function init (){
//ur code
}`

jquery: exclude external resources from $(window).load()

I need to execute some scripts when all the resources on my domain and subdomain are loaded, so I did this:
$(window).load(function(){
// al my functions here...
}
The problem is that there are some external resources (not on my domain and subdomain) that sometimes take longer to load. Is there a way to exclude external resources from the load event?
EDIT:
I was hoping to do something like:
$(window).not(".idontcare").load(function()
but it's not working
I guess your external resources rely on a src attribute.
If so, in your page source code you could set the src attribute of the resources you don't want to wait for, not as src but as external_src.
Then you could easily do:
$(document).ready(function(){
$(window).load(function(){
// all your functions here...
});
$('[external_src]').each(function() {
var external_src = $(this).attr("external_src");
$(this).attr("src", external_src); // now it starts to load
$(this).removeAttr("external_src"); // keep your DOM clean
//Or just one line:
//$(this).attr("src", $(this).attr("external_src")).removeAttr("external_src");
});
});
This way the external resources should start loading as soon as just the DOM is ready, without waiting for the full window load.
I have almost same case. But in my case, I want to exclude all iframes that load content from another site (e.g. youtube, vimeo etc). Found a work around, so the scenario is hide 'src' attribute from all iframes when DOM is ready and put it back when window is finish load all another content.
(function($){
//DOM is ready
$(document).ready(function(){
var frame = $('iframe'),
frameSrc = new Array();
if( frame.length ){
$.each( frame, function(i, f){
frameSrc[i] = $(f).attr('src');
//remove the src attribute so window will ignore these iframes
$(f).attr('src', '');
});
//window finish load
$(window).on('load',function(){
$.each( frame, function(a, x){
//put the src attribute value back
$(x).attr('src', frameSrc[a]);
});
});
}
});
})(jQuery);
You can mark all elements in your site that load external resources by adding a special class, and change the iframe with $('.special_class') or something like that. I dont know if this is the best way but at least it works great in my side :D
Unfortunately, the window.onload event is very strict. As you might know it will fire when all und every resource was transfered and loaded, images, iframes, everything. So the quick answer to your question is no, there is no easy-to-use way to tell that event to ignore external resources, it makes no difference there.
You would need to handle that yourself, which could be a tricky thing according to how those resources are included and located. You might even need to manipulate the source code before it gets delivered to accomplish that.
As far as I know, there is an async - tag for script tags. You can your includes to:
<script src="script_path" async="true"></script>
This will not include them to the event.
maybe
$(document).ready(...)
instead of $(window).load() will help?
The document ready event executes already when the HTML-Document is loaded and the DOM is ready, even if all the graphics haven’t loaded yet.

element width is undefined on document ready

I am trying to obtain an element width using the following code just before the </body>
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
var diff = $('div.canvas img.photo').get(1).width;
console.log(diff);
});
</script>
but it logs undefined. However, if I run $('div.canvas img.photo').get(1).width directly in the Chrome/Firebug console, it returns the correct width. The image is not being loaded with Javascript, so should be in place when the document ready fires. What am I doing wrong?
No, it shouldn't. document.ready fires when all HTML has been loaded, but not the images. If you want to wait until all images are loaded, use window.load.
Example:
$(window).load(function(){
var diff = $('div.canvas img.photo').get(1).width;
console.log(diff);
});
Also, as some people have pointed out, you were attempting to get the property ".width" twice.
If at all possible, set a width on the imagetags in CSS. That way, you can safely use document.ready for your code. Using window.load will naturally delay the execution of your script, could be a second, could be ten, depending on the speed of the clients connection, and the amount of content on your page. This could cause unwanted jumps and jitters if you're performing any styling.
img isn't being loaded on DOM ready. docs:
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.
change to this:
$(window).load(function(){
var diff = $('div.canvas img.photo').get(1).width;
console.log(diff.width);
});
Image's width would only be available when its loaded completely.
jQuery supports onload event on every images too.
You can use,
$('div.canvas img.photo').load(function(){
// here the image (or all images which match selector) has been loaded.
}
The problem is that your image is not loaded yet when you try to get its dimentions. To make it work wrap your code into $(window).load. Or another option. If you know the sizes of the image you can provide width and height attributes, then it's going to work even inside DOMContentLoaded. Sometimes it's preferable because onload event takes longer to fire then 'DOMContentLoaded'.
Otherwise you would need to use $(window).load, see #Andreas Carlbom answer.

How can I tell when all images on a page are loaded using jQuery?

I’m using jQuery for my project. $(function(){...}) fires the function “when the DOM is ready” — this doesn’t say that all images are loaded, right?
Is there an event that gets fired when every image is loaded too?
I guess you mean
http://api.jquery.com/ready/
versus
http://api.jquery.com/load-event/
Example: Run a function when the page is fully loaded including graphics.
$(window).load(function () {
// run code
});
without jQuery:
window.onload=function() {
alert(document.images.length);
}
You can check on load event of image tag. This will get fired when image loading completes.
$("img").load(function(){
// your code
});
window.onload will solve this, I wrote about this there: http://amrelgarhy.com/blog/how-to-tell-when-images-have-loaded/

Categories