How to reload a page only once everytime it gets loaded - javascript

I have a JSP page that is showing previous content even after deleting one of the content. I am working to find the problem but I need a quick fix for this. I'm weak in JavaScript so please help me out. I need a JavaScript that would reload the page automatically every time the page is visited. Reloading the page does solve the problem.

If you want to do it just once, I would use localStorage:
if (localStorage.getItem('loadedOnce') === 'true') {
// don't reload page, but clear localStorage value so it'll get reloaded next time
localStorage.removeItem('loadedOnce');
} else {
// set the flag and reload the page
localStorage.setItem('loadedOnce', 'true');
document.location.reload(true);
}
I would really recommend looking into why this is broken, instead of trying to hack around the problem.
Note:
This doesn't work in older browsers. See mdn's compatability table for more information (IE8 does support it however).

Based on #Omar's answer, and similar to tjameson's. It just uses cookies instead.
var int=self.setTimeout(function(){refresh()},1000);
function refresh() {
if (document.cookie.indexOf("reloaded") === -1){
document.cookie += ";reloaded";
document.location.reload(true);
}
else {
document.cookie = document.cookie.replace(/;reloaded/g, '');
}
}

Related

jQuery only working sporadically or on a page refresh/hard reload

I am using jQuery to read the URL of the page to determine which page the user is on and then change the background accordingly. My code works great, sometimes... I've tried using $(window).load(function() to no avail and the only answer I can find here is to use $( document ).ready(function() but that's not much help because that's how I wrote the code to begin with, and it's not working as it should. I also attempted to force the page to reload inside the function but that was pointless as well, ( I didn't have much hope for it anyway). When it doesn't work a simple click of the refresh button will get it to work. I have also tried putting the script tag in the header and footer, no difference. I have implemented the same code on different sites and in both cases, it works fine... I thought that maybe it was a caching issue but multiple hard reloads proved otherwise.
You can see for yourself at http://maisonshowroom.com/ click through the nav and the background is supposed to change for each page. I also have a console.log message that should reflect the URL, sometimes it's correct...but that just raises more questions for me, regardless if it's correct or not it should still have a background image rather than just being blank.
Here's my code
$(document).ready(function() {
//changes background images based on which page user is on//
var currentPage = window.location.href;
console.log(currentPage);
if (currentPage.includes('about')) {
$('.wrapper-inner').css('background-image',
'url(http://maisonshowroom.com/wp-content/uploads/2017/09/maison-
about.jpg)');
}
else if (currentPage.includes('services'))
{
$('.wrapper-inner').css('background-image', 'url(http://maisonshowroom.com/wp-content/uploads/2017/09/maison-service-e1506643269331.jpg)');
}
else if (currentPage.includes('products'))
{
$('.wrapper-inner').css('background-image', 'url(http://maisonshowroom.com/wp-content/uploads/2017/09/maison-product.jpg)');
}
else if (currentPage.includes('contact'))
{
$('.wrapper-inner').css('background-image', 'url(http://maisonshowroom.com/wp-content/uploads/2017/09/maison-contact.jpg)');
}
else {
$('.wrapper-inner').css('background-image', 'url(http://maisonshowroom.com/wp-content/uploads/2017/09/maison-about.jpg)');
}
});
Remove this line:
window.location.reload();
and fix this line :
'url(http://maisonshowroom.com/wp-content/uploads/2017/09/maison-
about.jpg)');
to:
$('.wrapper-inner').css('background-image',
'url(http://maisonshowroom.com/wp-content/uploads/2017/09/maison-about.jpg)');
One single line
All I needed to do was disable the AJAX page transition from the WordPress dashboard. Thanks, Patrick Evans, for pointing out that it was being handled by AJAX, I would have never guessed.

Trying to remove this code without the need to put it in a seperate page

My index.html page has a fancy animation to begin with it is essentially this code below...
$(document).ready(function() {
setTimeout(function() {
$("#loader-wrapper .loader-section, #textbit, #logo, #wrapper").hide("slow");
$("#wrapper").unwrap();
}, 11000);
});
..... so once this code has run its 11 seconds it all gets unwrapped and thats great... Problem is I have an a tag to get back to the index page at any time and I don't want people to have to wait for the intro animation to run before getting to the homepage every time....
I will not accept any answer that says .."do the animation on a seperate page" - the code has to be on the index page itself.
I was hoping there was some sort of jquery that will remove the code until the browser page has been refreshed, something like that.. Really appreciate any help here.
EDIT -- Getting some initial feedback that this is unclear ... in step for ...
User goes to index.html
the above code begins and lasts for 11 seconds.
then it gets unwrapped and disappears.
Seperatly while the user is enjoying the site they click on the "home" logo.
this takes people back to the index.html page
Unfortunately they have an 11 seconds wait every time and i want this to stop unless they refresh the browser or something.
You could use something like localStorage or cookies on your server side to manage this.
Here's the local storage example:
$(document).ready(function() {
if( !window.localStorage || !window.localStorage.getItem('hpAnim') ) {
setTimeout(function() {
$("#loader-wrapper .loader-section, #textbit, #logo, #wrapper").hide("slow");
$("#wrapper").unwrap();
}, 11000);
if( window.localStorage ) {
window.localStorage.setItem('hpAnim', true)
}
}
} );
So now (in IE8+) the second and future pageloads will not run the animation.
On the other hand if you've got a single page JavaScript app and you want it to re-run only after page refresh (as per comments on question), then you can skip local storage and simply set a global variable on window:
window.hasSeenAnimation = true
And then check that condition before running the animation again. After a page refresh that variable will be gone.
Set a cookie the 1st time that the users waits 11 secs
Can use https://github.com/carhartl/jquery-cookie or with native javascript code.
As well you can use a localstore var or url query
$(document).ready(function() {
if ($.cookie("index_viewed") == 1) {
return;
} else {
setTimeout(function() {
$("#loader-wrapper .loader-section, #textbit, #logo, #wrapper").hide("slow");
$("#wrapper").unwrap();
$.cookie("index_viewed", 1);
}, 11000);
}
});
You can set a $_GET variable and then check for this. If it's there, it must be an internal link so don't load the animation:
Home
<?php
if (!isset($_GET['noAnim']))
{
?>
<script>
// your animation script goes here....
</script>
<?php
}
?>
Assuming that you only want that animation to run at "startup" (when directly pointed) you could check the tab history count:
history.length
This will return a value higher than 1 only if any navigation took place on the tab (going to index from any other page).
This is not a perfect solution though:
Cross browser issues (some return 0, others 1)
Every navigation on this tab will produce history, hence, if you navigate to your website after checking any other page, history will return a value higher than the initial. (you can also check the document.referrer to ease this issue)
If you can't afford to skip the animation on those conditions you must persist the fact that the animation had already ran, and you should aim for Local Storage, for example (as mentioned earlier) http://www.w3schools.com/html/html5_webstorage.asp

Reset dropdown at page refresh or back/forward browser navigation

Is there a simple command to restart all, or some included javascripts? The problem I´ve got is that by refreshing page or pressing the back/forward key in the browser, some javascripts look like cached.
Maybe like codepen it does?
UPDATE:
I found out, that this is only a problem for my "dropdowns". So I have to reset them, if I refresh the browser and/or press back/forward. Any simple way?
UPDATE:
Ok, that works for me:
$(':input').not(":button").val('');
});
No, I found out that this is a "dropdown" problem - so, I want to
reset them by browser refresh and/or forward/backward.
To reset dropdowns to default value, you could use:
$(window).on("pageshow", function() {
$('select').prop('selectedIndex', function () {
var selected = $(this).children('[selected]').index();
return selected != -1 ? selected : 0;
});
});
This is because the browser used a cached version of the page when you clicked the back button, it is called a bfcache.
You could try to add an empty unload handler like $(window).unload(function(){}); to disable the cache.
More info here: http://madhatted.com/2013/6/16/you-do-not-understand-browser-history

Changing the 'src' attribute of an image using javascript

I'm using javascript, so that when a refresh button is clicked it begins to spin around until the refresh is completed. This is my function:
function RefreshHome() {
// Refreshes the home page via the image link.
// Make the refresh link animate.
var refresh = document.getElementById("refresh_button");
refresh.src = "images/refresh_animated.gif";
// Refresh the page.
window.location = "home.aspx";
return false;
}
This worked perfectly for a while then, as far as I can see, inexplicably stopped working! When the refresh button is clicked on now, the image just disappears.
Does anybody know why this might happen?
Just want to mention that this would be much easier in jQuery. You wouldn't need to worry so much about maintaining browser compatibility etc. either. As your project grows your code may become unwieldily, so even if you don't decide to use jQuery you should find a suitable framework for your needs.
var refresh = $("#refresh_button");
refresh.attr("src", "images/refresh_animated.gif");
Also be aware that an image that has no src shows up with a placeholder X on most browsers, and you can hide it with display:none; or using the refresh.hide() and refresh.show() methods in jQuery as needed.

Using Bookmarks with jQuery Address

I am using jQuery's Address plugin (website) to enable the back/forward buttons on my website. I would REALLY like to also have the ability for people to bookmark pages and to copy the address from the address bar and share it with friends.
Address claims it can do this, so then what am I doing wrong.
My code is
function BackButton() {
$.address.change(function(event) {
// do something depending on the event.value property, e.g.
// $('#content').load(event.value + '.xml');
});
$('a').click(function() {
$.address.value($(this).attr('href').replace(/^#/, ''));
});
}
BackButton() is then called on every AJAX pageload to ensure it works with the pages loaded by ajax.
Thanks for your help
looks like you copied directly from the example at the plugin's website. your address.change function does nothing, there are only two commented lines in there.
So I used
if ( $.address.value() !== "\/" ) {
window.location = "http://www.domainname.com/" + $.address.value()
}
to redirect the user to the correct page.
So is this correct? Or are their problems with it?
What would be the benefits of using the $.address.init function of jQuery.Address?
Also this forces them to wait until the page (&javascript) is loaded to see any content. comments?

Categories

Resources