How to autorefresh if page failed to load? - javascript

I had come up with these solution:
My Solution / Expectation:Put a setTimeout(). So if the page will still not load, in 5sec, I will reload(auto) the page.
See code:
var time;
window.onload = function(){
time = setTimeout(function(){ document.location.reload(); }, 5000);
};
$(document).ready(function(){
clearTimeout(time);
});
My Problem with this solution, is that the page will still reload even if the page has already loaded.
I want to cancel the setTimeout if the page has already loaded, but the code above does not working as expected.
Someone could help me, I really needing this to my thesis. Please help. Thanks in adv.

This will help..as the document itself have readyState variable
var time;
window.onload = function() {
time = setTimeout(function() {
if (document.readyState === 'complete') {
clearTimeout(time);
} else {
document.location.reload();
}
}, 5000);
};

Instead of the jQuery, use document.readyState like so:
var time;
window.onload = function(){
time = setTimeout(function(){
document.location.reload();
}, 5000);
};
document.onreadystatechange = function() {
if (document.readyState == "complete") {
clearTimeout(time);
}
}

Related

Stop page load after 10 sec javascript

I am facing a problem, on my website i am using
<script type="text/javascript">
window.onload = function() {
var countdownElement = document.getElementById('countdown'),
downloadButton = document.getElementById('new_download'),
seconds = 10 ,
second = 0,
interval;
downloadButton.style.display = 'none';
interval = setInterval(function() {
if (second >= seconds) {
downloadButton.style.display = 'block';
countdownElement.style.display = 'none';
clearInterval(interval);
}
second++;
}, 1000);
}
</script>
But some google ads keep on loading and this function don't work. so i thought to stop page load after 10 sec with this script in footer of page
<script type="text/javascript">
setTimeout( function(){
window.stop()
} , 10000 );
</script>
But this is not working, is there any way i can stop page load after some time or skip google ads load time from page load time or other method except window.onload function
Heres a quick jquery code i wrote which worked for me...although i had no google ads. and i got rid of the setInterval()
hope it helps..
$("document").ready(function() {
$("#new_download").css({
"display":"none"
});
setTimeout(displaydbutton,10000);
}
function displaydbutton(){
$("#dload").css({
"display":"block"
});
clearTimeout();
});

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)
}
}

Load script after page load from back button

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

How to refresh the page only one time after 5 sec in JavaScript?

Does anyone know how to refresh the page only one time after 5 sec in JavaScript?
I have the following script to refresh the page after 5 sec:
setTimeout(function () {
window.location.reload(1);
}, 5000); // After 5 secs
But somehow this is refresh every 5 sec instead of just once time after the 1st 5 sec. Does anyone know how to fix this issue?
I think better solution is check document.referer and compare with document.location
if (document.referrer !== document.location.href) {
setTimeout(function() {
document.location.reload()
}, 5000);
}
You can try this in jsfiddle: https://jsfiddle.net/ga0Lrurj/
This is by far the simplest and lightest solution:
setTimeout(function () {
if(window.location.hash != '#r') {
window.location.hash = 'r';
window.location.reload(1);
}
}, 5000); // After 5 secs
You need a way to identify a reloaded page. The easiest way (imo) would be to controll this server side. Check a get-variable and include the js-code if it does not exist.
Also, I see people suggesting cookies. I don't like using cookies for minor stuff like this.
You could try something like:
// Get all get-variables
var queryDict = {}
location.search.substr(1).split("&").forEach(function(item) {queryDict[item.split("=")[0]] = item.split("=")[1]})
// Check if reloaded is set
if (queryDict['reloaded'] == 'undefined') {
// Check if url contains any get-variables
if (Object.keys(queryDict).length == 0) {
var redirect = document.URL + '?reloaded';
}
else {
var redirect = document.URL + '&reloaded';
}
// The timeout
setTimeout(function () {
window.location = redirect;
}, 5000);
}
You need to kept this script after doing something like insertions or updations or any other task then it will reload your page after 5 seconds for once. It works for me while uploading pictures i kept this scripts after uploading my file rather than kept it in window.load or documents.ready function its work for like a charm. here is my script. May this helps you solve your problem
<script type="text/javascript">
$(window).load(function () {
$('#<%=FileUpload1.ClientID%>').uploadify({
'swf': 'fy/uploadify.swf',
'cancelImg': 'fy/uploadify-cancel.png',
'buttonText': 'Browse Files',
'uploader': 'Gallery.ashx',
'folder': 'uploads',
'fileDesc': 'Image Files',
'fileExt': '*.jpg;*.jpeg;*.gif;*.png',
'multi':true,
'auto': false,
'formData':{'paid':<%= Request.QueryString["PhotoAlbumID"] %>},
'onUploadStart': function (file) {
$("#<%=FileUpload1.ClientID%>").uploadify("settings", 'Txt', $('#password').val());
$( document ).ready(function() {
}); setTimeout(function() { window.location=window.location;},3000);
}
});
});
</script>

Javascript only works when with alerts

The following code loads a youtube vidéo in a player.
If I remove the two "alert", it doesn't work anymore...
ytplayer = document.getElementById("ytPlayer");
alert('ok');
if (ytplayer) {
alert('ok');
loadVideo(url, start);
}
Can someone help me?
you are probably invoking the code before the page loads. With the alert, js execution stops, allowing the page to load. If this is correct, you need to look into the window.onload callback or possibly document.ready
window.onload = function(){
// load the vid here
}
Invoke the function after the page has been loaded completely.
window.onload = function() {
loadVideo(url, start);
}
I fixed the problem with the following :
ytplayer = document.getElementById("ytPlayer");
if (ytplayer) {
setTimeout( function() { loadVideo(url, start); }, 1000);
}
Thanks for your answers.
Did you use Ajax Request ?
if YES then
put you code that didnt work at the end of
AjaxObject.onreadystatechange = function () {
if (AjaxObject.readyState == 4) {
.
.
.
.
.
// PUT HERE
}
}
then IF NO
put your code in function and return false or true
like this
ytplayer = document.getElementById("ytPlayer");
alert('ok');
if (ytplayer) {
//alert('ok');
loadVideo(url, start);
return true;
}
hope helps

Categories

Resources