Load script after page load from back button - javascript

Is there a way to fire a javascript function after everything on the page has loaded, after the back button has been used?
Basically I have search results which I store with localStorage which works great but I can't get the function to fire after everything else has loaded. It does fire but get overwritten by another function so want to wait until everything has finished.
I've tried:
window.onload
document.onload
if(window.attachEvent) {
window.attachEvent('onload', yourFunctionName);
} else {
if(window.onload) {
var curronload = window.onload;
var newonload = function() {
curronload();
yourFunctionName();
};
window.onload = newonload;
} else {
window.onload = yourFunctionName;
}
}
document.onreadystatechange = function () {
if (document.readyState == "complete") {
myFunction();
}
}
Is there an absolute way after hitting the back button, knowing when the page has absolutely finished loading?
I'm using javascript, not jQuery

Related

execute js function after reloading page [duplicate]

I'm trying to refresh a page and then run a function once the refresh has been completed. However the code I have now, runs the function and then it only refreshes it, meaning I lose what the function did. Is there a way to solve this?
My code
function reloadP(){
document.location.reload();
myFunction();
}
<button onclick: "reloadP()">Click</button>
You need to call myFunction() when the page is loaded.
window.onload = myFunction;
If you only want to run it when the page is reloaded, not when it's loaded for the first time, you could use sessionStorage to pass this information.
window.onload = function() {
var reloading = sessionStorage.getItem("reloading");
if (reloading) {
sessionStorage.removeItem("reloading");
myFunction();
}
}
function reloadP() {
sessionStorage.setItem("reloading", "true");
document.location.reload();
}
DEMO
function myFunction() {
document.getElementById("welcome").textContent = "Welcome back!";
}
window.onload = function() {
var reloading = sessionStorage.getItem("reloading");
if (reloading) {
sessionStorage.removeItem("reloading");
myFunction();
}
}
function reloadP() {
sessionStorage.setItem("reloading", "true");
document.location.reload();
}
DEMO: https://jsfiddle.net/barmar/5sL3hd74/
Adding to #Barmar answer... In case you'd like to use session storage only when a button in the page is clicked and not when reloading with the browser button, you can use sessionStorage.clear() or sessionStorage.removeItem() once you've executed the function after loading the window.
So, let's say we have:
let restart = sessionStorage.getItem("restart")
Set restart boolean to true as a session storage and reload:
resetBtn.addEventListener("click", () => {
sessionStorage.setItem("restart", "true")
location.reload()
})
Once the window is reloaded we can execute the following function:
window.onload = () => {
if(restart){
// Do something
sessionStorage.clear() // This cleans all the session storage
// If you want to remove ONLY the item from the storage use:
// sessionStorage.removeItem("restart")
}
};
So, if now the user reloads the page with the browser button it will reload with the session storage cleaned. Meaning, no functions will be executed after window load.
In my case i used Barmar's solution. I have a modal popup form, i want to submit the form then automatically refresh the page and finally success message on reloaded page.
var form = document.getElementById('EditUserInfosForm')
form.addEventListener('submit', function () {
sessionStorage.setItem("reloading", "true");
document.location.reload();
})
window.onload = function () {
var reloading = sessionStorage.getItem("reloading");
if (reloading) {
sessionStorage.removeItem("reloading");
$('#success-message-modal').modal('show')
}
}
Probably simplest approach.
HTML Button
Reload button (credits):
<!-- index.html -->
<button onClick="window.location.reload();">Refresh Page</button>
JS Code
Run your code after reload:
// index.js
window.addEventListener("load", (event) => {
YourFunction(); // already declared somewhere else
});
You may not use event variable at all.
https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event#examples

Don't show page until content has fully loaded

I am creating a landing page which should exist in two languages. The texts that should be shown are in two JSON files, called accordingly "ru.json" and "en.json". When a user clicks on the "Change language" button, the following function is executed:
function changeLang(){
if (userLang == 'ru') {
userLang = 'en';
document.cookie = 'language=en';
}
else {
userLang = 'ru';
document.cookie = 'language=ru';
}
var translate = new Translate();
var attributeName = 'data-tag';
translate.init(attributeName, userLang);
translate.process();
}
Where Translate() is the following:
function Translate() {
//initialization
this.init = function(attribute, lng){
this.attribute = attribute;
if (lng !== 'en' && lng !== 'ru') {
this.lng = 'en'
}
else {
this.lng = lng;
}
};
//translate
this.process = function(){
_self = this;
var xrhFile = new XMLHttpRequest();
//load content data
xrhFile.open("GET", "./resources/js/"+this.lng+".json", false);
xrhFile.onreadystatechange = function ()
{
if(xrhFile.readyState === 4)
{
if(xrhFile.status === 200 || xrhFile.status == 0)
{
var LngObject = JSON.parse(xrhFile.responseText);
var allDom = document.getElementsByTagName("*");
for(var i =0; i < allDom.length; i++){
var elem = allDom[i];
var key = elem.getAttribute(_self.attribute);
if(key != null) {
elem.innerHTML = LngObject[key] ;
}
}
}
}
};
xrhFile.send();
}
Everything works fine, however, when a user opens the page for the first time, if his Internet connection is bad, he just sees the elements of the page without text. It is just 1-2 seconds, but still annoying.
The question is, is there any way to check the text has loaded and display the page elements only on this condition?
You can use $(document).ready() in this way
$(document).ready(function(){
//your code here;
})
You can use the JavaScript pure load event in this way
window.addEventListener('load', function () {
//your code right here;
}, false);
Source: Here
translate.process() is asynchronous code which needs to make a call to a server and wait for its response. What it means is that, when you call this function, it goes in the background to go do its own thing while the rest of the page continues loading. That is why the user sees the page while this function is still running.
One minimal way I can think around this is by adding this to your css files in the head tag.
body { display: none }
And then, under this.process function, after the for loop ends, add
document.body.style.display = 'block'
If you want to suppori IE8:
document.onreadystatechange = function () {
if (document.readyState == "interactive") {
// run some code.
}
}
Put the code you want to execute when the user initially loads the page in a DOMContentLoaded event handler like below:
document.addEventListener('DOMContentLoaded', function() {
console.log('Whereas code execution in here will be deffered until the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.');
});
console.log('This will log immediatley');
It's important to note that DOMContentLoaded is different than the load event

Multiple window onload functions with only Javascript

I have an external JS file that adds a window.onload function to the page.
The basic premise is that it loads up a popup window on your website whenever the user clicks on certain link class. It's written in PHP / JS so assume that the function works by itself.
Inside this JS file has the following code.
window.onload = function() {
var anchors = document.getElementsByClassName("vyper-triggers");
for (var i = 0; i < anchors.length; i++) {
var anchor = anchors[i];
anchor.onclick = function() {
if (isMobile.any()) {
window.open("$url");
} else {
document.getElementById("clickonthis").click();
}
}
}
}
Now my problem is when my user wants to add 2 different popup windows, the window.onload function doesn't stack. Also because this is an embedded javascript that my user adds himself, there is no way for me to put both functions inside one big window.onload function.
My user might put one JS file in one area of their site, and another JS file in another area, if that makes sense.
So how do I make it so that the window.onload function will stack no matter the placing of these external JS files on the page and considering that each function must be kept separate?
Rather than setting window.onload, you should use addEventListener. Listeners added this way will stack automatically.
window.addEventListener('load', function() {
console.log('First listener');
});
window.addEventListener('load', function() {
console.log('Second listener');
});
window.addEventListener('load', function() {
console.log('Third listener');
});
If you have to support versions of IE before IE9, there's a polyfill which will make this work correctly.
Probably you have multiple files and u want to check something onload.
Let's implement a basic function to add other functions and run all of them when the event onload is triggered.
So, first we check if windows.onload has a function object if not add our function. If is contains a function object merge it with our function like this:
function addLoadEvent(callback) {
const previous = window.onload
if (typeof previous === 'function') {
window.onload = (e) => {
if (previous) previous(e)
callback(e)
}
}
...
}
This is an example how to use it:
function addLoadEvent(callback) {
const previous = window.onload
if (typeof previous === 'function') {
window.onload = (e) => {
if (previous) previous(e)
callback(e)
}
} else {
window.onload = callback
}
}
function func1() {
console.log('This is the first.')
}
function func2() {
console.log('This is the second.')
}
addLoadEvent(func1);
addLoadEvent(func2);
addLoadEvent(() => {
console.log('This is the third.')
document.body.style.backgroundColor = '#EFDF95'
})

anonymous window.setTimeout function reloading page

Using Tampermonkey to change the behavior of a website. Have some problems with a website with the following code:
<script language="JavaScript">
if (typeof jQuery != 'undefined') {
jQuery(window).load(function() {
window.setTimeout(function() {
window.location.replace(window.location.href);
}, 180E3);
});
}
</script>
How does one remove/prevent it reloading the page?
Without messing that much with jQuery, if your script runs before that piece of code you can do the following:
jQuery.fn.load = function() {
console.log("Tried to reload the page!")
}
// Then the following, outputs 'Tried to reload the page!' and does nothing else
jQuery(window).load(function() {
// code
})
If you still need the load function afterwards you could do the following:
var oldLoad = jQuery.fn.load
var undesiredCallback = "function() {
window.setTimeout(function() {
window.location.replace(window.location.href);
}, 180E3);
}"
jQuery.fn.load = function(callback) {
if(callback.toString() !== undesiredCallback) {
oldLoad(callback);
}
}
But it's browser dependent and very unreliable
Another way would be adding a onbeforeunload event, but that would pop a prompt on your tab:
window.onbeforeunload = function() {
return "Stay here please";
}
You can also override setTimeout functionallity.
var oldSetTimeout = window.setTimeout;
window.setTimeout = function(func,interval){
if(typeof func === "function" && func.toString().indexOf('window.location.replace(window.location.href)') > -1){
/*do nothing*/
}else{
oldSetTimeout(func,interval)
}
}

Javascript - How to detect if document has loaded (IE 7/Firefox 3)

I want to call a function after a document loads, but the document may or may not have finished loading yet. If it did load, then I can just call the function. If it did NOT load, then I can attach an event listener. I can't add an eventlistener after onload has already fired since it won't get called. So how can I check if the document has loaded? I tried the code below but it doesn't entirely work. Any ideas?
var body = document.getElementsByTagName('BODY')[0];
// CONDITION DOES NOT WORK
if (body && body.readyState == 'loaded') {
DoStuffFunction();
} else {
// CODE BELOW WORKS
if (window.addEventListener) {
window.addEventListener('load', DoStuffFunction, false);
} else {
window.attachEvent('onload', DoStuffFunction);
}
}
There's no need for all the code mentioned by galambalazs. The cross-browser way to do it in pure JavaScript is simply to test document.readyState:
if (document.readyState === "complete") { init(); }
This is also how jQuery does it.
Depending on where the JavaScript is loaded, this can be done inside an interval:
var readyStateCheckInterval = setInterval(function() {
if (document.readyState === "complete") {
clearInterval(readyStateCheckInterval);
init();
}
}, 10);
In fact, document.readyState can have three states:
Returns "loading" while the document is loading, "interactive" once it is finished parsing but still loading sub-resources, and "complete" once it has loaded.
-- document.readyState at Mozilla Developer Network
So if you only need the DOM to be ready, check for document.readyState === "interactive". If you need the whole page to be ready, including images, check for document.readyState === "complete".
No need for a library. jQuery used this script for a while, btw.
http://dean.edwards.name/weblog/2006/06/again/
// Dean Edwards/Matthias Miller/John Resig
function init() {
// quit if this function has already been called
if (arguments.callee.done) return;
// flag this function so we don't do the same thing twice
arguments.callee.done = true;
// kill the timer
if (_timer) clearInterval(_timer);
// do stuff
};
/* for Mozilla/Opera9 */
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", init, false);
}
/* for Internet Explorer */
/*#cc_on #*/
/*#if (#_win32)
document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
var script = document.getElementById("__ie_onload");
script.onreadystatechange = function() {
if (this.readyState == "complete") {
init(); // call the onload handler
}
};
/*#end #*/
/* for Safari */
if (/WebKit/i.test(navigator.userAgent)) { // sniff
var _timer = setInterval(function() {
if (/loaded|complete/.test(document.readyState)) {
init(); // call the onload handler
}
}, 10);
}
/* for other browsers */
window.onload = init;
You probably want to use something like jQuery, which makes JS programming easier.
Something like:
$(document).ready(function(){
// Your code here
});
Would seem to do what you are after.
if(document.readyState === 'complete') {
DoStuffFunction();
} else {
if (window.addEventListener) {
window.addEventListener('load', DoStuffFunction, false);
} else {
window.attachEvent('onload', DoStuffFunction);
}
}
If you actually want this code to run at load, not at domready (ie you need the images to be loaded as well), then unfortunately the ready function doesn't do it for you. I generally just do something like this:
Include in document javascript (ie always called before onload fired):
var pageisloaded=0;
window.addEvent('load',function(){
pageisloaded=1;
});
Then your code:
if (pageisloaded) {
DoStuffFunction();
} else {
window.addEvent('load',DoStuffFunction);
}
(Or the equivalent in your framework of preference.) I use this code to do precaching of javascript and images for future pages. Since the stuff I'm getting isn't used for this page at all, I don't want it to take precedence over the speedy download of images.
There may be a better way, but I've yet to find it.
Mozila Firefox says that onreadystatechange is an alternative to DOMContentLoaded.
// alternative to DOMContentLoaded
document.onreadystatechange = function () {
if (document.readyState == "complete") {
initApplication();
}
}
In DOMContentLoaded the Mozila's doc says:
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).
I think load event should be used for a full document+resources loading.
The above one with JQuery is the easiest and mostly used way. However you can use pure javascript but try to define this script in the head so that it is read at the beginning. What you are looking for is window.onload event.
Below is a simple script that I created to run a counter. The counter then stops after 10 iterations
window.onload=function()
{
var counter = 0;
var interval1 = setInterval(function()
{
document.getElementById("div1").textContent=counter;
counter++;
if(counter==10)
{
clearInterval(interval1);
}
},1000);
}
Try this:
var body = document.getElementsByTagName('BODY')[0];
// CONDITION DOES NOT WORK
if ((body && body.readyState == 'loaded') || (body && body.readyState == 'complete') ) {
DoStuffFunction();
} else {
// CODE BELOW WORKS
if (window.addEventListener) {
window.addEventListener('load', DoStuffFunction, false);
} else {
window.attachEvent('onload',DoStuffFunction);
}
}
I have other solution, my application need to be started when new object of MyApp is created, so it looks like:
function MyApp(objId){
this.init=function(){
//.........
}
this.run=function(){
if(!document || !document.body || !window[objId]){
window.setTimeout(objId+".run();",100);
return;
}
this.init();
};
this.run();
}
//and i am starting it
var app=new MyApp('app');
it is working on all browsers, that i know.

Categories

Resources