JS window.onload why don't wait loaded - javascript

Why it works without waiting for the page to be full loaded. Also, how can I run a function when the whole page is full loaded on Javascript?

It depends on your definition of "loaded".
The load event will fire...
[...]once a web page has completely loaded all content (including images, script files, CSS files, etc.). (Source)
This is the case here. All the images and script files and CSS files in the original HTML document have been loaded! However, the "loaded" state in case of Twitter is a state in which a script will later initiate the loading of new elements. That is outside the scope of the original page load.
If you want to wait for what you call "loaded", you'd have to ask yourself technically what point that is. I guess the answer would be something like "when element X is visible". In that case you can install a MutationObserver to listen on that element getting added/modified, after identifying what element you want to wait for by checking the DOM in your browser console. (The worse solution would be an interval that checks if that element exists yet.)
For Twitter, this works for me for example (watching for the first story to be loaded):
const observer = new MutationObserver(mutations => {
if (mutations.some(mutation => {
return Array.from(mutation.addedNodes).some(node => node.querySelector('article'))
})) {
setTimeout(() => { // Wait for all the updates of this frame to go through
console.log('Page fully loaded!')
}, 0)
observer.disconnect()
}
})
observer.observe(document, {
attributes: false,
childList: true,
characterData: false,
subtree: true
})

change your onload function syntax to any one of the following and try
window.addEventListener('load', (event) => {
console.log('page is fully loaded');
});
with onload
window.onload = (event) => {
console.log('page is fully loaded');
};

Related

How can I run some JS once the whole interface will be loaded? [duplicate]

I'm writing a Greasemonkey user script, and want the specific code to execute when the page completely finishes loading since it returns a div count that I want to be displayed.
The problem is, that this particular page sometimes takes a bit before everything loads.
I've tried, document $(function() { }); and $(window).load(function(){ }); wrappers. However, none seem to work for me, though I might be applying them wrong.
Best I can do is use a setTimeout(function() { }, 600); which works, although it's not always reliable.
What is the best technique to use in Greasemonkey to ensure that the specific code will execute when the page finishes loading?
Greasemonkey (usually) doesn't have jQuery. So the common approach is to use
window.addEventListener('load', function() {
// your code here
}, false);
inside your userscript
This is a common problem and, as you've said, waiting for the page load is not enough -- since AJAX can and does change things long after that.
There is a standard(ish) robust utility for these situations. It's the waitForKeyElements() utility.
Use it like so:
// ==UserScript==
// #name _Wait for delayed or AJAX page load
// #include http://YOUR_SERVER.COM/YOUR_PATH/*
// #require http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// #require https://gist.github.com/raw/2625891/waitForKeyElements.js
// #grant GM_addStyle
// ==/UserScript==
/*- The #grant directive is needed to work around a major design
change introduced in GM 1.0.
It restores the sandbox.
*/
waitForKeyElements ("YOUR_jQUERY_SELECTOR", actionFunction);
function actionFunction (jNode) {
//-- DO WHAT YOU WANT TO THE TARGETED ELEMENTS HERE.
jNode.css ("background", "yellow"); // example
}
Give exact details of your target page for a more specific example.
As of Greasemonkey 3.6 (November 20, 2015) the metadata key #run-at supports the new value document-idle.
Simply put this in the metadata block of your Greasemonkey script:
// #run-at document-idle
The documentation describes it as follows:
The script will run after the page and all resources (images, style sheets, etc.) are loaded and page scripts have run.
Brock's answer is good, but I'd like to offer another solution to the AJAX problem that is more modern and elegant.
Since his script, like most others, also uses setInterval() to check periodically (300ms), it can't respond instantly and there is always a delay. And other solutions uses onload events, which will often fire earlier than you want on dynamic pages.
You can use MutationObserver() to listen for DOM changes and respond to them as soon as the element is created
(new MutationObserver(check)).observe(document, {childList: true, subtree: true});
function check(changes, observer) {
if(document.querySelector('#mySelector')) {
observer.disconnect();
// code
}
}
Though since check() fires on every single DOM change, this may be slow if the DOM changes very often or your condition takes a long time to evaluate, so instead of observing document, try to limit the scope by observing a DOM subtree that's as small as possible.
This method is very general and can be applied to many situations. To respond multiple times, just don't disconnect the observer when triggered.
Another use case is if you're not looking for any specific element, but just waiting for the page to stop changing, you can combine this with a countdown that resets every time something changes on the page.
var observer = new MutationObserver(resetTimer);
var timer = setTimeout(action, 3000, observer); // wait for the page to stay still for 3 seconds
observer.observe(document, {childList: true, subtree: true});
// reset timer every time something changes
function resetTimer(changes, observer) {
clearTimeout(timer);
timer = setTimeout(action, 3000, observer);
}
function action(observer) {
observer.disconnect();
// code
}
This method is so versatile, you can listen for attribute and text changes as well. Just set attributes and characterData to true in the options
observer.observe(document, {childList: true, attributes: true, characterData: true, subtree: true});
wrapping my scripts in $(window).load(function(){ }) never failed for me.
maybe your page has finished, but there is still some ajax content being loaded.
if that is the case, this nice piece of code from Brock Adams can help you:
https://gist.github.com/raw/2625891/waitForKeyElements.js
i usually use it to monitor for elements that appears on postback.
use it like this: waitForKeyElements("elementtowaitfor", functiontocall)
If you want to manipulate nodes like getting value of nodes or changing style, you can wait for these nodes using this function
const waitFor = (...selectors) => new Promise(resolve => {
const delay = 500
const f = () => {
const elements = selectors.map(selector => document.querySelector(selector))
if (elements.every(element => element != null)) {
resolve(elements)
} else {
setTimeout(f, delay)
}
}
f()
})
then use promise.then
// scripts don't manipulate nodes
waitFor('video', 'div.sbg', 'div.bbg').then(([video, loading, videoPanel])=>{
console.log(video, loading, videoPanel)
// scripts may manipulate these nodes
})
or use async&await
//this semicolon is needed if none at end of previous line
;(async () => {
// scripts don't manipulate nodes
const [video, loading, videoPanel] = await waitFor('video','div.sbg','div.bbg')
console.log(video, loading, video)
// scripts may manipulate these nodes
})()
Here is an example icourse163_enhance
To detect if the XHR finished loading in the webpage then it triggers some function.
I get this from How do I use JavaScript to store "XHR finished loading" messages in the console in Chrome? and it real works.
//This overwrites every XHR object's open method with a new function that adds load and error listeners to the XHR request. When the request completes or errors out, the functions have access to the method and url variables that were used with the open method.
//You can do something more useful with method and url than simply passing them into console.log if you wish.
//https://stackoverflow.com/questions/43282885/how-do-i-use-javascript-to-store-xhr-finished-loading-messages-in-the-console
(function() {
var origOpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function(method, url) {
this.addEventListener('load', function() {
console.log('XHR finished loading', method, url);
display();
});
this.addEventListener('error', function() {
console.log('XHR errored out', method, url);
});
origOpen.apply(this, arguments);
};
})();
function display(){
//codes to do something;
}
But if there're many XHRs in the page, I have no idea how to filter the definite one XHR.
Another method is waitForKeyElements() which is nice.
https://gist.github.com/BrockA/2625891
There's sample for Greasemonkey use.
Run Greasemonkey script on the same page, multiple times?

Changing text of a website using Tampermonkey

so basically I want to change a W Text into B. My code below is working fine but there is a lag when you refresh the page where it shows the W text then replaces it with a B. My second problem is that every 20 refreshes or so, the B Text doesn't replace the original. Can someone plz help fix my code so it doesn't make these 2 mistakes Thanks.
window.onload = function () {
/* Add your logic here */
var my_div = document.getElementsByClassName('c')[3]
my_div.firstChild.nodeValue = 'B'
}
An onload handler will run once all resources on the page have finished downloading. On larger pages with images and external scripts and such, this could take a while, especially on bad connections.
Attach a DOMContentLoaded listener instead, which will run as soon as the DOM structure has been downloaded and parsed by the browser.
If the document may already be interactive by the time the userscript runs, then don't attach a listener, just run a function that changes the text immediately:
if (window.top === window) {
const fn = () => {
var my_div = document.getElementsByClassName('c')[3];
my_div.firstChild.nodeValue='B'
};
if (document.readyState === 'interactive' || document.readyState === 'complete') {
fn();
} else {
window.addEventListener('DOMContentLoaded', fn);
}
}
But the document in your link is huge, and even DOM parsing takes a long time, then the above may not be fast enough, in which case you could attach a MutationObserver to the document at the beginning of pageload (with #run-at document-start and instant script injection), and change the document.getElementsByClassName('c')[3] as soon as it exists in the document, like this:
// ==UserScript==
// #name New Userscript
// #include /^https://fork-accessuh-uh-edu-e3e0cca90dc751a6.sitemod.io/logout.phpsitemod/
// #run-at document-start
// ==/UserScript==
const cs = document.getElementsByClassName('c');
new MutationObserver((mutations, observer) => {
if (!cs[3]) {
return;
}
cs[3].firstChild.nodeValue='B'
observer.disconnect();
})
.observe(document.documentElement, { childList: true, subtree: true });
document-start isn't entirely reliable, though - it will sometimes take some time to execute such a script. If you happen to be in an environment where the script doesn't run immediately, enable experimental instant script injection too, via Tampermonkey settings (Config mode: Advanced, scroll to the very bottom, Inject Mode: Instant).

Clicking a button in Javascript(tampermonkey) [duplicate]

I'm writing a Greasemonkey user script, and want the specific code to execute when the page completely finishes loading since it returns a div count that I want to be displayed.
The problem is, that this particular page sometimes takes a bit before everything loads.
I've tried, document $(function() { }); and $(window).load(function(){ }); wrappers. However, none seem to work for me, though I might be applying them wrong.
Best I can do is use a setTimeout(function() { }, 600); which works, although it's not always reliable.
What is the best technique to use in Greasemonkey to ensure that the specific code will execute when the page finishes loading?
Greasemonkey (usually) doesn't have jQuery. So the common approach is to use
window.addEventListener('load', function() {
// your code here
}, false);
inside your userscript
This is a common problem and, as you've said, waiting for the page load is not enough -- since AJAX can and does change things long after that.
There is a standard(ish) robust utility for these situations. It's the waitForKeyElements() utility.
Use it like so:
// ==UserScript==
// #name _Wait for delayed or AJAX page load
// #include http://YOUR_SERVER.COM/YOUR_PATH/*
// #require http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// #require https://gist.github.com/raw/2625891/waitForKeyElements.js
// #grant GM_addStyle
// ==/UserScript==
/*- The #grant directive is needed to work around a major design
change introduced in GM 1.0.
It restores the sandbox.
*/
waitForKeyElements ("YOUR_jQUERY_SELECTOR", actionFunction);
function actionFunction (jNode) {
//-- DO WHAT YOU WANT TO THE TARGETED ELEMENTS HERE.
jNode.css ("background", "yellow"); // example
}
Give exact details of your target page for a more specific example.
As of Greasemonkey 3.6 (November 20, 2015) the metadata key #run-at supports the new value document-idle.
Simply put this in the metadata block of your Greasemonkey script:
// #run-at document-idle
The documentation describes it as follows:
The script will run after the page and all resources (images, style sheets, etc.) are loaded and page scripts have run.
Brock's answer is good, but I'd like to offer another solution to the AJAX problem that is more modern and elegant.
Since his script, like most others, also uses setInterval() to check periodically (300ms), it can't respond instantly and there is always a delay. And other solutions uses onload events, which will often fire earlier than you want on dynamic pages.
You can use MutationObserver() to listen for DOM changes and respond to them as soon as the element is created
(new MutationObserver(check)).observe(document, {childList: true, subtree: true});
function check(changes, observer) {
if(document.querySelector('#mySelector')) {
observer.disconnect();
// code
}
}
Though since check() fires on every single DOM change, this may be slow if the DOM changes very often or your condition takes a long time to evaluate, so instead of observing document, try to limit the scope by observing a DOM subtree that's as small as possible.
This method is very general and can be applied to many situations. To respond multiple times, just don't disconnect the observer when triggered.
Another use case is if you're not looking for any specific element, but just waiting for the page to stop changing, you can combine this with a countdown that resets every time something changes on the page.
var observer = new MutationObserver(resetTimer);
var timer = setTimeout(action, 3000, observer); // wait for the page to stay still for 3 seconds
observer.observe(document, {childList: true, subtree: true});
// reset timer every time something changes
function resetTimer(changes, observer) {
clearTimeout(timer);
timer = setTimeout(action, 3000, observer);
}
function action(observer) {
observer.disconnect();
// code
}
This method is so versatile, you can listen for attribute and text changes as well. Just set attributes and characterData to true in the options
observer.observe(document, {childList: true, attributes: true, characterData: true, subtree: true});
wrapping my scripts in $(window).load(function(){ }) never failed for me.
maybe your page has finished, but there is still some ajax content being loaded.
if that is the case, this nice piece of code from Brock Adams can help you:
https://gist.github.com/raw/2625891/waitForKeyElements.js
i usually use it to monitor for elements that appears on postback.
use it like this: waitForKeyElements("elementtowaitfor", functiontocall)
If you want to manipulate nodes like getting value of nodes or changing style, you can wait for these nodes using this function
const waitFor = (...selectors) => new Promise(resolve => {
const delay = 500
const f = () => {
const elements = selectors.map(selector => document.querySelector(selector))
if (elements.every(element => element != null)) {
resolve(elements)
} else {
setTimeout(f, delay)
}
}
f()
})
then use promise.then
// scripts don't manipulate nodes
waitFor('video', 'div.sbg', 'div.bbg').then(([video, loading, videoPanel])=>{
console.log(video, loading, videoPanel)
// scripts may manipulate these nodes
})
or use async&await
//this semicolon is needed if none at end of previous line
;(async () => {
// scripts don't manipulate nodes
const [video, loading, videoPanel] = await waitFor('video','div.sbg','div.bbg')
console.log(video, loading, video)
// scripts may manipulate these nodes
})()
Here is an example icourse163_enhance
To detect if the XHR finished loading in the webpage then it triggers some function.
I get this from How do I use JavaScript to store "XHR finished loading" messages in the console in Chrome? and it real works.
//This overwrites every XHR object's open method with a new function that adds load and error listeners to the XHR request. When the request completes or errors out, the functions have access to the method and url variables that were used with the open method.
//You can do something more useful with method and url than simply passing them into console.log if you wish.
//https://stackoverflow.com/questions/43282885/how-do-i-use-javascript-to-store-xhr-finished-loading-messages-in-the-console
(function() {
var origOpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function(method, url) {
this.addEventListener('load', function() {
console.log('XHR finished loading', method, url);
display();
});
this.addEventListener('error', function() {
console.log('XHR errored out', method, url);
});
origOpen.apply(this, arguments);
};
})();
function display(){
//codes to do something;
}
But if there're many XHRs in the page, I have no idea how to filter the definite one XHR.
Another method is waitForKeyElements() which is nice.
https://gist.github.com/BrockA/2625891
There's sample for Greasemonkey use.
Run Greasemonkey script on the same page, multiple times?

Userscript to wait for page to load before executing code techniques?

I'm writing a Greasemonkey user script, and want the specific code to execute when the page completely finishes loading since it returns a div count that I want to be displayed.
The problem is, that this particular page sometimes takes a bit before everything loads.
I've tried, document $(function() { }); and $(window).load(function(){ }); wrappers. However, none seem to work for me, though I might be applying them wrong.
Best I can do is use a setTimeout(function() { }, 600); which works, although it's not always reliable.
What is the best technique to use in Greasemonkey to ensure that the specific code will execute when the page finishes loading?
Greasemonkey (usually) doesn't have jQuery. So the common approach is to use
window.addEventListener('load', function() {
// your code here
}, false);
inside your userscript
This is a common problem and, as you've said, waiting for the page load is not enough -- since AJAX can and does change things long after that.
There is a standard(ish) robust utility for these situations. It's the waitForKeyElements() utility.
Use it like so:
// ==UserScript==
// #name _Wait for delayed or AJAX page load
// #include http://YOUR_SERVER.COM/YOUR_PATH/*
// #require http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// #require https://gist.github.com/raw/2625891/waitForKeyElements.js
// #grant GM_addStyle
// ==/UserScript==
/*- The #grant directive is needed to work around a major design
change introduced in GM 1.0.
It restores the sandbox.
*/
waitForKeyElements ("YOUR_jQUERY_SELECTOR", actionFunction);
function actionFunction (jNode) {
//-- DO WHAT YOU WANT TO THE TARGETED ELEMENTS HERE.
jNode.css ("background", "yellow"); // example
}
Give exact details of your target page for a more specific example.
As of Greasemonkey 3.6 (November 20, 2015) the metadata key #run-at supports the new value document-idle.
Simply put this in the metadata block of your Greasemonkey script:
// #run-at document-idle
The documentation describes it as follows:
The script will run after the page and all resources (images, style sheets, etc.) are loaded and page scripts have run.
Brock's answer is good, but I'd like to offer another solution to the AJAX problem that is more modern and elegant.
Since his script, like most others, also uses setInterval() to check periodically (300ms), it can't respond instantly and there is always a delay. And other solutions uses onload events, which will often fire earlier than you want on dynamic pages.
You can use MutationObserver() to listen for DOM changes and respond to them as soon as the element is created
(new MutationObserver(check)).observe(document, {childList: true, subtree: true});
function check(changes, observer) {
if(document.querySelector('#mySelector')) {
observer.disconnect();
// code
}
}
Though since check() fires on every single DOM change, this may be slow if the DOM changes very often or your condition takes a long time to evaluate, so instead of observing document, try to limit the scope by observing a DOM subtree that's as small as possible.
This method is very general and can be applied to many situations. To respond multiple times, just don't disconnect the observer when triggered.
Another use case is if you're not looking for any specific element, but just waiting for the page to stop changing, you can combine this with a countdown that resets every time something changes on the page.
var observer = new MutationObserver(resetTimer);
var timer = setTimeout(action, 3000, observer); // wait for the page to stay still for 3 seconds
observer.observe(document, {childList: true, subtree: true});
// reset timer every time something changes
function resetTimer(changes, observer) {
clearTimeout(timer);
timer = setTimeout(action, 3000, observer);
}
function action(observer) {
observer.disconnect();
// code
}
This method is so versatile, you can listen for attribute and text changes as well. Just set attributes and characterData to true in the options
observer.observe(document, {childList: true, attributes: true, characterData: true, subtree: true});
wrapping my scripts in $(window).load(function(){ }) never failed for me.
maybe your page has finished, but there is still some ajax content being loaded.
if that is the case, this nice piece of code from Brock Adams can help you:
https://gist.github.com/raw/2625891/waitForKeyElements.js
i usually use it to monitor for elements that appears on postback.
use it like this: waitForKeyElements("elementtowaitfor", functiontocall)
If you want to manipulate nodes like getting value of nodes or changing style, you can wait for these nodes using this function
const waitFor = (...selectors) => new Promise(resolve => {
const delay = 500
const f = () => {
const elements = selectors.map(selector => document.querySelector(selector))
if (elements.every(element => element != null)) {
resolve(elements)
} else {
setTimeout(f, delay)
}
}
f()
})
then use promise.then
// scripts don't manipulate nodes
waitFor('video', 'div.sbg', 'div.bbg').then(([video, loading, videoPanel])=>{
console.log(video, loading, videoPanel)
// scripts may manipulate these nodes
})
or use async&await
//this semicolon is needed if none at end of previous line
;(async () => {
// scripts don't manipulate nodes
const [video, loading, videoPanel] = await waitFor('video','div.sbg','div.bbg')
console.log(video, loading, video)
// scripts may manipulate these nodes
})()
Here is an example icourse163_enhance
To detect if the XHR finished loading in the webpage then it triggers some function.
I get this from How do I use JavaScript to store "XHR finished loading" messages in the console in Chrome? and it real works.
//This overwrites every XHR object's open method with a new function that adds load and error listeners to the XHR request. When the request completes or errors out, the functions have access to the method and url variables that were used with the open method.
//You can do something more useful with method and url than simply passing them into console.log if you wish.
//https://stackoverflow.com/questions/43282885/how-do-i-use-javascript-to-store-xhr-finished-loading-messages-in-the-console
(function() {
var origOpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function(method, url) {
this.addEventListener('load', function() {
console.log('XHR finished loading', method, url);
display();
});
this.addEventListener('error', function() {
console.log('XHR errored out', method, url);
});
origOpen.apply(this, arguments);
};
})();
function display(){
//codes to do something;
}
But if there're many XHRs in the page, I have no idea how to filter the definite one XHR.
Another method is waitForKeyElements() which is nice.
https://gist.github.com/BrockA/2625891
There's sample for Greasemonkey use.
Run Greasemonkey script on the same page, multiple times?

execute function after complete page load [duplicate]

This question already has answers here:
How to make JavaScript execute after page load?
(25 answers)
Closed 1 year ago.
I am using following code to execute some statements after page load.
<script type="text/javascript">
window.onload = function () {
newInvite();
document.ag.src="b.jpg";
}
</script>
But this code does not work properly. The function is called even if some images or elements are loading. What I want is to call the function the the page is loaded completely.
this may work for you :
document.addEventListener('DOMContentLoaded', function() {
// your code here
}, false);
or
if your comfort with jquery,
$(document).ready(function(){
// your code
});
$(document).ready() fires on DOMContentLoaded, but this event is not being fired consistently among browsers. This is why jQuery will most probably implement some heavy workarounds to support all the browsers. And this will make it very difficult to "exactly" simulate the behavior using plain Javascript (but not impossible of course).
as Jeffrey Sweeney and J Torres suggested, i think its better to have a setTimeout function, before firing the function like below :
setTimeout(function(){
//your code here
}, 3000);
JavaScript
document.addEventListener('readystatechange', event => {
// When HTML/DOM elements are ready:
if (event.target.readyState === "interactive") { //does same as: ..addEventListener("DOMContentLoaded"..
alert("hi 1");
}
// When window loaded ( external resources are loaded too- `css`,`src`, etc...)
if (event.target.readyState === "complete") {
alert("hi 2");
}
});
same for jQuery:
$(document).ready(function() { //same as: $(function() {
alert("hi 1");
});
$(window).load(function() {
alert("hi 2");
});
NOTE: - Don't use the below markup ( because it overwrites other same-kind declarations ) :
document.onreadystatechange = ...
I'm little bit confuse that what you means by page load completed, "DOM Load" or "Content Load" as well? In a html page load can fire event after two type event.
DOM load: Which ensure the entire DOM tree loaded start to end. But not ensure load the reference content. Suppose you added images by the img tags, so this event ensure that all the img loaded but no the images properly loaded or not. To get this event you should write following way:
document.addEventListener('DOMContentLoaded', function() {
// your code here
}, false);
Or using jQuery:
$(document).ready(function(){
// your code
});
After DOM and Content Load: Which indicate the the DOM and Content load as well. It will ensure not only img tag it will ensure also all images or other relative content loaded. To get this event you should write following way:
window.addEventListener('load', function() {...})
Or using jQuery:
$(window).on('load', function() {
console.log('All assets are loaded')
})
If you can use jQuery, look at load. You could then set your function to run after your element finishes loading.
For example, consider a page with a simple image:
<img src="book.png" alt="Book" id="book" />
The event handler can be bound to the image:
$('#book').load(function() {
// Handler for .load() called.
});
If you need all elements on the current window to load, you can use
$(window).load(function () {
// run code
});
If you cannot use jQuery, the plain Javascript code is essentially the same amount of (if not less) code:
window.onload = function() {
// run code
};
If you wanna call a js function in your html page use onload event. The onload event occurs when the user agent finishes loading a window or all frames within a FRAMESET. This attribute may be used with BODY and FRAMESET elements.
<body onload="callFunction();">
....
</body>
You're best bet as far as I know is to use
window.addEventListener('load', function() {
console.log('All assets loaded')
});
The #1 answer of using the DOMContentLoaded event is a step backwards since the DOM will load before all assets load.
Other answers recommend setTimeout which I would strongly oppose since it is completely subjective to the client's device performance and network connection speed. If someone is on a slow network and/or has a slow cpu, a page could take several to dozens of seconds to load, thus you could not predict how much time setTimeout will need.
As for readystatechange, it fires whenever readyState changes which according to MDN will still be before the load event.
Complete
The state indicates that the load event is about to fire.
This way you can handle the both cases - if the page is already loaded or not:
document.onreadystatechange = function(){
if (document.readyState === "complete") {
myFunction();
}
else {
window.onload = function () {
myFunction();
};
};
}
you can try like this without using jquery
window.addEventListener("load", afterLoaded,false);
function afterLoaded(){
alert("after load")
}
Alternatively you can try below.
$(window).bind("load", function() {
// code here });
This works in all the case. This will trigger only when the entire page is loaded.
window.onload = () => {
// run in onload
setTimeout(() => {
// onload finished.
// and execute some code here like stat performance.
}, 10)
}
If you're already using jQuery, you could try this:
$(window).bind("load", function() {
// code here
});
I can tell you that the best answer I found is to put a "driver" script just after the </body> command. It is the easiest and, probably, more universal than some of the solutions, above.
The plan: On my page is a table. I write the page with the table out to the browser, then sort it with JS. The user can resort it by clicking column headers.
After the table is ended a </tbody> command, and the body is ended, I use the following line to invoke the sorting JS to sort the table by column 3. I got the sorting script off of the web so it is not reproduced here. For at least the next year, you can see this in operation, including the JS, at static29.ILikeTheInternet.com. Click "here" at the bottom of the page. That will bring up another page with the table and scripts. You can see it put up the data then quickly sort it. I need to speed it up a little but the basics are there now.
</tbody></body><script type='text/javascript'>sortNum(3);</script></html>
MakerMikey
I tend to use the following pattern to check for the document to complete loading. The function returns a Promise (if you need to support IE, include the polyfill) that resolves once the document completes loading. It uses setInterval underneath because a similar implementation with setTimeout could result in a very deep stack.
function getDocReadyPromise()
{
function promiseDocReady(resolve)
{
function checkDocReady()
{
if (document.readyState === "complete")
{
clearInterval(intervalDocReady);
resolve();
}
}
var intervalDocReady = setInterval(checkDocReady, 10);
}
return new Promise(promiseDocReady);
}
Of course, if you don't have to support IE:
const getDocReadyPromise = () =>
{
const promiseDocReady = (resolve) =>
{
const checkDocReady = () =>
((document.readyState === "complete") && (clearInterval(intervalDocReady) || resolve()));
let intervalDocReady = setInterval(checkDocReady, 10);
}
return new Promise(promiseDocReady);
}
With that function, you can do the following:
getDocReadyPromise().then(whatIveBeenWaitingToDo);
call a function after complete page load set time out
setTimeout(function() {
var val = $('.GridStyle tr:nth-child(2) td:nth-child(4)').text();
for(var i, j = 0; i = ddl2.options[j]; j++) {
if(i.text == val) {
ddl2.selectedIndex = i.index;
break;
}
}
}, 1000);
Try this jQuery:
$(function() {
// Handler for .ready() called.
});
Put your script after the completion of body tag...it works...

Categories

Resources