multiple $(document).ready and $(window).load in $(document).ready - javascript

I got 2 questions. First of all, this is not my work. I'm currently looking at somebody else's JavaScript files. I can't give the exact code but I can show what I'm wondering.
In the JavaScript files I see a lot of $(document).ready(function(){});. I know what $(document).ready does, the callback function will be called when the DOM tree is loaded. Is there any reason why somebody would use more than one $(document).ready callback? I don't get the point.
Also, another thing I saw was a $(window).load inside a $(document).ready, like this:
$(document).ready(function() {
$(window).load(function() {
//...
});
});
From what I know, $(window).load() is called when everything of a page is loaded, like assets and images etc. I would think $(window).load() is the last thing called, after $(document).ready. Is there any time where $(window).load is called BEFORE $(document).ready and is there any reason why you would put a $(window).load inside a $(document).ready?

Yes, jQuery grants that ready event will be called before load. Even in IE8- (where DOMContentLoaded is not supported) it works in that way. But let's look at the following code:
<!doctype html>
<title>Ready vs load test</title>
<style>body {white-space: pre}</style>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
~function () {
function log(msg) {
document.body.innerHTML += msg + "\n";
}
function handler(msg) {
return function () {
log(msg);
}
}
$(window).load(handler("5. load #1"));
$(document).ready(handler("1. ready #2"));
$(window).load(handler("6. load #3"));
$(document).ready(handler("2. ready #4"));
$(document).ready(function () {
log("3. ready #5");
$(window).load(handler("8. load #6"));
});
$(document).ready(handler("4. ready #7"));
$(window).load(handler("7. load #8"));
}();
</script>
The result is
1. ready #2
2. ready #4
3. ready #5
4. ready #7
5. load #1
6. load #3
7. load #8
8. load #6
Look at lines 7 and 8. The load handled attached from ready event is the last one. So by using this way we can ensure that all previously added (during scripts parsing and exection) load handlers have already been called.
so using $(window).load outside the $(document).ready and inside doesn't change that much from how it'd affect how stuff work?
Actually it can affect script execution. The first version works and the second doesn't:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$(window).load(function () {
$.magic.value = 12;
});
});
</script>
<script>
$(window).load(function () {
$.magic = {};
});
</script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
});
$(window).load(function () {
$.magic.value = 12;
});
</script>
<script>
$(window).load(function () {
$.magic = {};
});
</script>

$(document).ready kicks in when all nodes of the DOM have been loaded but not necessarily their content, that's what's $(window).load is for, e.g. an img-ele can be present, yet it's content – the image – hasn't been loaded.
So, you're right, use each listener only once and don't nest them.

Related

How to wait to execute JS until readyState == Complete for document and window? [duplicate]

I need to execute some JavaScript code when the page has fully loaded. This includes things like images.
I know you can check if the DOM is ready, but I don’t know if this is the same as when the page is fully loaded.
That's called load. It came waaaaay before DOM ready was around, and DOM ready was actually created for the exact reason that load waited on images.
window.addEventListener('load', function () {
alert("It's loaded!")
})
For completeness sake, you might also want to bind it to DOMContentLoaded, which is now widely supported
document.addEventListener("DOMContentLoaded", function(event){
// your code here
});
More info: https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded
Usually you can use window.onload, but you may notice that recent browsers don't fire window.onload when you use the back/forward history buttons.
Some people suggest weird contortions to work around this problem, but really if you just make a window.onunload handler (even one that doesn't do anything), this caching behavior will be disabled in all browsers. The MDN documents this "feature" pretty well, but for some reason there are still people using setInterval and other weird hacks.
Some versions of Opera have a bug that can be worked around by adding the following somewhere in your page:
<script>history.navigationMode = 'compatible';</script>
If you're just trying to get a javascript function called once per-view (and not necessarily after the DOM is finished loading), you can do something like this:
<img src="javascript:location.href='javascript:yourFunction();';">
For example, I use this trick to preload a very large file into the cache on a loading screen:
<img src="bigfile"
onload="this.location.href='javascript:location.href=\'javascript:doredir();\';';doredir();">
Try this it Only Run After Entire Page Has Loaded
By Javascript
window.onload = function(){
// code goes here
};
By Jquery
$(window).bind("load", function() {
// code goes here
});
Try this code
document.onreadystatechange = function () {
if (document.readyState == "complete") {
initApplication();
}
}
visit https://developer.mozilla.org/en-US/docs/DOM/document.readyState for more details
Javascript using the onLoad() event, will wait for the page to be loaded before executing.
<body onload="somecode();" >
If you're using the jQuery framework's document ready function the code will load as soon as the DOM is loaded and before the page contents are loaded:
$(document).ready(function() {
// jQuery code goes here
});
the window.onload event will fire when everything is loaded, including images etc.
You would want to check the DOM ready status if you wanted your js code to execute as early as possible, but you still need to access DOM elements.
You may want to use window.onload, as the docs indicate that it's not fired until both the DOM is ready and ALL of the other assets in the page (images, etc.) are loaded.
In modern browsers with modern javascript (>= 2015) you can add type="module" to your script tag, and everything inside that script will execute after whole page loads. e.g:
<script type="module">
alert("runs after") // Whole page loads before this line execute
</script>
<script>
alert("runs before")
</script>
also older browsers will understand nomodule attribute. Something like this:
<script nomodule>
alert("tuns after")
</script>
For more information you can visit javascript.info.
And here's a way to do it with PrototypeJS:
Event.observe(window, 'load', function(event) {
// Do stuff
});
The onload property of the GlobalEventHandlers mixin is an event
handler for the load event of a Window, XMLHttpRequest, element,
etc., which fires when the resource has loaded.
So basically javascript already has onload method on window which get executed which page fully loaded including images...
You can do something:
var spinner = true;
window.onload = function() {
//whatever you like to do now, for example hide the spinner in this case
spinner = false;
};
Completing the answers from #Matchu and #abSiddique.
This:
window.addEventListener('load', (event) => {
console.log('page is fully loaded');
});
Is the same as this but using the onload event handler property:
window.onload = (event) => {
console.log('page is fully loaded');
};
Source:
https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event
Live example here:
https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event#live_example
If you need to use many onload use $(window).load instead (jQuery):
$(window).load(function() {
//code
});
2019 update: This is was the answer that worked for me. As I needed multiple ajax requests to fire and return data first to count the list items.
$(document).ajaxComplete(function(){
alert("Everything is ready now!");
});

How can I make this function execute automatically / on load [duplicate]

Traditionally, to call a JavaScript function once the page has loaded, you'd add an onload attribute to the body containing a bit of JavaScript (usually only calling a function)
<body onload="foo()">
When the page has loaded, I want to run some JavaScript code to dynamically populate portions of the page with data from the server. I can't use the onload attribute since I'm using JSP fragments, which have no body element I can add an attribute to.
Is there any other way to call a JavaScript function on load? I'd rather not use jQuery as I'm not very familiar with it.
If you want the onload method to take parameters, you can do something similar to this:
window.onload = function() {
yourFunction(param1, param2);
};
This binds onload to an anonymous function, that when invoked, will run your desired function, with whatever parameters you give it. And, of course, you can run more than one function from inside the anonymous function.
Another way to do this is by using event listeners, here's how you use them:
document.addEventListener("DOMContentLoaded", function() {
your_function(...);
});
Explanation:
DOMContentLoaded It means when the DOM objects of the document are fully loaded and seen by JavaScript. Also this could have been "click", "focus"...
function() Anonymous function, will be invoked when the event occurs.
Your original question was unclear, assuming Kevin's edit/interpretation is correct, then this first option doesn't apply
The typical options is using the onload event:
<body onload="javascript:SomeFunction()">
....
You can also place your JavaScript at the very end of the body; it won't start executing until the doc is complete.
<body>
...
<script type="text/javascript">
SomeFunction();
</script>
</body>
Another option is to use a JS framework which intrinsically does this:
// jQuery
$(document).ready( function () {
SomeFunction();
});
function yourfunction() { /* do stuff on page load */ }
window.onload = yourfunction;
Or with jQuery if you want:
$(function(){
yourfunction();
});
If you want to call more than one function on page load, take a look at this article for more information:
Using Multiple JavaScript Onload Functions
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
function codeAddress() {
alert('ok');
}
window.onload = codeAddress;
</script>
</head>
<body>
</body>
</html>
You have to call the function you want to be called on load (i.e., load of the document/page).
For example, the function you want to load when document or page load is called "yourFunction". This can be done by calling the function on load event of the document. Please see the code below for more detail.
Try the code below:
<script src="js/jquery-1.11.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
yourFunction();
});
function yourFunction(){
//some code
}
</script>
here's the trick (works everywhere):
r(function(){
alert('DOM Ready!');
});
function r(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()}
For detect loaded html (from server) inserted into DOM use MutationObserver or detect moment in your loadContent function when data are ready to use
let ignoreFirstChange = 0;
let observer = (new MutationObserver((m, ob)=>
{
if(ignoreFirstChange++ > 0) console.log('Element added on', new Date());
}
)).observe(content, {childList: true, subtree:true });
// TEST: simulate element loading
let tmp=1;
function loadContent(name) {
setTimeout(()=>{
console.log(`Element ${name} loaded`)
content.innerHTML += `<div>My name is ${name}</div>`;
},1500*tmp++)
};
loadContent('Senna');
loadContent('Anna');
loadContent('John');
<div id="content"><div>

Run Javascript code on Page Load [duplicate]

This question already has answers here:
Onclick() function on working
(4 answers)
Closed 9 years ago.
I am using the jquery tool bootstrap wizard and there is a function within it to start the wizard that I want to load up automatically when I go to a page.
Here is my code:
$('#open-wizard').click(function (e) {
e.preventDefault();
wizard.show();
});
I need to have this code run whenever I load the page. I know for functions you could just add, not sure how I do this with my code, I tried to put it in a function and didn't work.
window.onload = load();
function load() {
//javascript function here
}
when using window.onload you do not need the perenthesis. change load() to load..
function load() {
//javascript function here
}
window.onload = load;
Yes,and i suggest u put the js import tags at the bottom of the page file.
eg:
<scrpit ...
<script type="text/javascript" src="../js/bootstrap.min.js"></script>
</body>
</html>
document.ready (jQuery)
$(document).ready(function()
{
// executes when HTML-Document is loaded and DOM is ready
alert("(document).ready was called - document is ready!");
});
document.ready will execute right after the HTML document is loaded property, and the DOM is ready
window.load (Built-in JavaScript)
$(window).load(function()
{
// executes when complete page is fully loaded, including all frames, objects and images
alert("(window).load was called - window is loaded!");
});
The window.load however will wait for the page to be fully loaded, this includes inner frames, images etc.
all you need is $(document).ready();
$(document).ready(function () {
wizard.show();
});

More efficient way to wait for all images to load in jQuery

I'm using a mix of .ready() and .load() to execute my desired function.
jQuery(document).ready(function($) {
$("img").load(function() {
// Function goes here
});
});
As you can see, this waits for the DOM to be ready, then on each <img> load, it executes the code.
If I only had one image to load this would be simple.
But the problem is -- what if I have 10 images to be loaded? The function will be called 10 times due to each image loading one by one, and that's not a very efficient way to go about it just to achieve what I want.
So here's the question -- is there a more efficient way to wait for all images to load, then execute the function once?
You could do something like this to avoid having your function run multiple times.
jQuery(document).ready(function($) {
var nrOfImages = $("img").length;
$("img").load(function() {
if(--nrOfImages == 0)
{
// Function goes here
}
});
});
jQuery(window).load(function() {
alert("page finished loading now.");
});
jQuery(window).load(...) will be triggered after all content on the page has been loaded. This different from jQuery(document).load(...) which is triggered after the DOM has been loaded. I think this will solve your issue.
If anybody wants to know, my final result was this:
(function($) {
$(window).load(function(){
// Function goes here
});
})(jQuery);
that's because
jQuery(window).load(function($) {});
isn't a jQuery object, as referenced in this question:
Calling jQuery on (window).load and passing variable for 'No Conflict' code

How do I call a JavaScript function on page load?

Traditionally, to call a JavaScript function once the page has loaded, you'd add an onload attribute to the body containing a bit of JavaScript (usually only calling a function)
<body onload="foo()">
When the page has loaded, I want to run some JavaScript code to dynamically populate portions of the page with data from the server. I can't use the onload attribute since I'm using JSP fragments, which have no body element I can add an attribute to.
Is there any other way to call a JavaScript function on load? I'd rather not use jQuery as I'm not very familiar with it.
If you want the onload method to take parameters, you can do something similar to this:
window.onload = function() {
yourFunction(param1, param2);
};
This binds onload to an anonymous function, that when invoked, will run your desired function, with whatever parameters you give it. And, of course, you can run more than one function from inside the anonymous function.
Another way to do this is by using event listeners, here's how you use them:
document.addEventListener("DOMContentLoaded", function() {
your_function(...);
});
Explanation:
DOMContentLoaded It means when the DOM objects of the document are fully loaded and seen by JavaScript. Also this could have been "click", "focus"...
function() Anonymous function, will be invoked when the event occurs.
Your original question was unclear, assuming Kevin's edit/interpretation is correct, then this first option doesn't apply
The typical options is using the onload event:
<body onload="javascript:SomeFunction()">
....
You can also place your JavaScript at the very end of the body; it won't start executing until the doc is complete.
<body>
...
<script type="text/javascript">
SomeFunction();
</script>
</body>
Another option is to use a JS framework which intrinsically does this:
// jQuery
$(document).ready( function () {
SomeFunction();
});
function yourfunction() { /* do stuff on page load */ }
window.onload = yourfunction;
Or with jQuery if you want:
$(function(){
yourfunction();
});
If you want to call more than one function on page load, take a look at this article for more information:
Using Multiple JavaScript Onload Functions
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
function codeAddress() {
alert('ok');
}
window.onload = codeAddress;
</script>
</head>
<body>
</body>
</html>
You have to call the function you want to be called on load (i.e., load of the document/page).
For example, the function you want to load when document or page load is called "yourFunction". This can be done by calling the function on load event of the document. Please see the code below for more detail.
Try the code below:
<script src="js/jquery-1.11.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
yourFunction();
});
function yourFunction(){
//some code
}
</script>
here's the trick (works everywhere):
r(function(){
alert('DOM Ready!');
});
function r(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()}
For detect loaded html (from server) inserted into DOM use MutationObserver or detect moment in your loadContent function when data are ready to use
let ignoreFirstChange = 0;
let observer = (new MutationObserver((m, ob)=>
{
if(ignoreFirstChange++ > 0) console.log('Element added on', new Date());
}
)).observe(content, {childList: true, subtree:true });
// TEST: simulate element loading
let tmp=1;
function loadContent(name) {
setTimeout(()=>{
console.log(`Element ${name} loaded`)
content.innerHTML += `<div>My name is ${name}</div>`;
},1500*tmp++)
};
loadContent('Senna');
loadContent('Anna');
loadContent('John');
<div id="content"><div>

Categories