how to refresh the browser after the page is loaded - javascript

I have a scenario to refresh the browser after the page is loaded for first time or one time.
Because the data is not showing properly when the pages is loaded,and when i refresh the browser it is showing.I don't know the reason.
Many Thanks

So you only want the browser to refresh once? Do something like this.
window.onload = function(){
if(!document.location.hash){
window.location = "#loaded";
}
}
or jquery
$(document).ready(function(){
if(document.location.hash){
window.location = "#loaded";
}
});
But in all honesty this is just a temporary solution. As much as you try to cover it up with quick fixes. I guarantee it will come back to haunt you. Well written and structured code will last a lifetime and can always be reused on future projects.

Invariably, you're going to have to use some JavaScript. What you want is for your refresh code to run when the page is completely loaded. You could use the HTML onload event, but there are problems with this (e.g. it will fire before any images are loaded). I would suggest using JQuery's ready() event, if you want to be sure it fires after the entire page is loaded.
Example:
// NOTE: This will only work with JQuery loaded.
$(document).ready(function(){
location.reload(true);
});
Making this only fire on the first page load is a bit more tricky. You could add an anchor suffix to the URL to keep track of whether you've refreshed the page yet or not, and then only refresh if it is not present in the URL:
$(document).ready(function(){
if(location.hash != "#")
{
// Set the URL to whatever it was plus "#".
// (The page will NOT automatically reload.)
location = "#";
// Reload the page.
location.reload(true);
}
});
Alternatively, you could use the query string, since this will automatically refresh the page when changed:
$(document).ready(function(){
var marker = 'r'; // 'r' is for "refreshed"
if(location.search != "?"+marker)
{
// Set the URL to whatever it was plus "?r".
// (This will automatically force a page reload.)
location = "?"+marker;
}
});
Caveat: With either of these samples, if your user bookmarks the page after the "#" or "?r" tag has been added to the URL, the page won't refresh when they revisit the page. If you want it to be bulletproof, you might have to use a cookie instead.

Related

Handling url targeted PHP page with custom jQuery loaded content

First I used include('pageName.php'); for every page I wanted to load.
Now I decided to rewrite everything and to load a page in a <div id="page_content"></div> with the jQuery function: $('#page_content').load(pageurl, {access:true});
I hope this is the best practice. Because I want to reduce load time on my web application by not refreshing the whole website with all CSS and JS files but just to refresh content when clicked on a new page.
Currently I am using the following function to load pages into the division and to pushState to history:
//Dynload pages
$("a[rel='dynload']").click(function(e) {
e.preventDefault();
var page = $(this).attr("page");
var pageurl = "pages/" + page + ".php";
$('#page_content').load(pageurl, {access:true});
if(pageurl!=window.location){
window.history.pushState({path:pageurl},'',page);
}
//stop refreshing to the page given in
return false;
});
This works perfectly.
I have this button that triggers this function and gives for attribute page="index_content" . The function will load this page to the division and the state is being pushed into the history.
However. We get an url something like this: https://mywebsite.com/index_content
The problem is, when I load this specific URL into my browser I get : "Page not found" ofcourse, because it is trying to search for the index_content folder which does not exist.
Is there a way to check the url by my PHP/jQuery script and to load the correct page into the division? If not, how can I solve this for a generic case.
When I add a new page, I want to spend no- to very less time on the pageswitcher function.
In that way I can also handle non-existing pages.
Thanks in advance!

Loading a page from hash on refresh

So I wrote this piece of JavaScript using the JQuery library. Its functionality is to have the pages load inside of a div instead of an entire page (to make modifying the layout way easier).
I've made it so it successfully saves the 'file URL' in the hash and I've made it so it loads correctly, but I can't for the life of me figure out how to go to that page.
When I try to go to a page with the hash in the name (so for example refreshing a page, or going through a link/URL) it replicates itself (I think) two times inside each other. You can see it happening live at overeten.be and then try to refresh a random page except the main one.
Could someone help me with this problem? Thanks in advance!
$("document").ready(function(){
$('._body').load("pages/default.html");
var locationhash = window.location.hash.replace('#','');
if ((locationhash=='pages/default.html')||(locationhash=='')){
console.log("no page, "+locationhash);
} else{
$('._body').load(window.location.hash);
console.log(locationhash);
}
$('.menubundle a, footer a').on('click', function (e) {
e.preventDefault();
var page = $(this).attr('href');
$('._body').fadeOut(1000,function(){
document.location.hash = page;
$('._body').load(page).fadeIn(1000);
});
});
});
The problem is on this line:
$('._body').load(window.location.hash);
If you inspect window.location.hash, you get this:
window.location.hash
"#pages/over_eten/feit.html"
That URL points to the current page. What you really want is this:
window.location.hash.slice(1) // Skip the first character
"pages/over_eten/feit.html"
On a side note, it seems weird to me that you have two calls to $('._body').load(). The first one seems like it belongs right above console.log('No page...') instead.

How to check page is reloading or refreshing using jquery or javascript?

I have to do some kind of operation on the page refresh or reload. that is when I hit next page or Filter or refresh on the grid. I need to show some confirmation box over this Events.
is there any event which can tell you page is doing filer? refresh or paging? using javascript?
Thanks
If it is refreshing (or the user is leaving the website/closing the browser), window.onunload will fire.
// From MDN
window.onunload = unloadPage;
function unloadPage()
{
alert("unload event detected!");
}
https://developer.mozilla.org/en/DOM/window.onunload
If you just want a confirmation box to allow them to stay, use this:
window.onbeforeunload = function() {
return "Are you sure you want to navigate away?";
}
You can create a hidden field and set its value on first page load. When the page is loaded again, you can check the hidden field. If it's empty then the page is loaded for the first time, else it's refreshed. Some thing like this:
HTML
<body onLoad="CheckPageLoad();">
<input type="hidden" name="visit" id="visit" value="" />
</body>
JS
function CheckPageLoad() {
if (document.getElementById("visit").value == "") {
// This is a fresh page load
document.getElementById("visit").value = "1";
}
else {
// This is a page refresh
}
}​
There are some clarification notes on wrestling with this I think are critical.
First, the refresh/hidden field system works on the beginning of the new page copy and after, not on leaving the first page copy.
From my research of this method and a few others, there is no way, primarily due to privacy standards, to detect a refresh of a page during unload or earlier. only after the load of the new page and later.
I had a similar issue request, but basically it was terminate session on exit of page, and while looking through that, found that a browser treats a reload/refresh as two distinct pieces:
close the current window (fires onbeforeunload and onunload js events).
request the page as if you never had it. Session on server of course has no issue, but no querystring changes/added values to the page's last used url.
These happen in just that order as well. Only a custom or non standard browser will behave differently.
$(function () {
if (performance.navigation.type == 1) {
yourFunction();
}
});
More about PerformanceNavigation object returned by performance.navigation

Javascript: check if the url is changed or not?

My url format is like :
http://domain.in/home
http://domain.in/books/notes
http://domain.in/books/notes/copy
I've called a javascript function on window.load to check if the url has changed or not.
If the url has been changed then code is executed else it will return and checks again after 5 sec.
My code is :
window.onload = function(){
setInterval(function(){
page_open();
}, 5000);
};
function page_open(){
var pages=unescape(location.href);
pages=pages.substr( pages.lastIndexOf("studysquare.in/") + 15 );
// gives book if url is http://studysquare.in/book
//alert("pages"+pages+"\n\n recent"+recent);
if (pages==recent) { return; }
recent=pages;
alert("Reached down now the code will execute.");
}
The problem now is : when the url is like :
http://domain.in/book
Single level deep, then everything works fine. But when the url is like
http://domain.in/book/copy or http://domain.in/book/copy/notes
Then nothing works.....
Any help to check 3 level deep url change in javascript every 5 sec ? :)
Hi sorry I forgot to tell that... I've .htaccess file which doesnt allow to navigate the page when any length url after the domain.in/ is written.... that means only single page remains open and not affected by the url change...
When the user changes the URL, the browser unloads the entire page they're currently on (including your javascript, hence it stops running) and then loads the next page. No javascript is able to run across page changes. You can't monitor a change in the URL like you're doing if they're navigating to another page.
The best way to catch a change in the URL is to add an onUnload event to the body object to fire your javascript when the browser unloads the page just before starting to load the new page the user has requested -- but I'm not sure that's going to help achieve your goal of tracking their recent page views (if that's what you're looking to do).
Sounds like a history plugin such as jQuery address would help you a lot.
It lets you handle the event when the URL is changed, so you can load in new content as required.

Force page reload with html anchors (#) - HTML & JS

Say I'm on a page called /example#myanchor1 where myanchor is an anchor in the page.
I'd like to link to /example#myanchor2, but force the page to reload while doing so.
The reason is that I run js to detect the anchor from the url at the page load.
The problem (normally expected behavior) here though, is that the browser just sends me to that specific anchor on the page without reloading the page.
How would I go about doing so? JS is OK.
I would suggest monitoring the anchor in the URL to avoid a reload, that's pretty much the point of using anchors for control-flow. But still here goes. I'd say the easiest way to force a reload using a simple anchor-link would be to use
where in place of $random insert a random number (assuming "dummy" is not interpreted server side). I'm sure there's a way to reload the page after setting the anchor, but it's probably more difficult then simply reacting to the anchor being set and do the stuff you need at that point.
Then again, if you reload the page this way, you can just put myanchor2 as a query parameter instead, and render your stuff server side.
Edit
Note that the link above will reload in all circumstances, if you only need to reload if you're not already on the page, you need to have the dummy variable be more predictable, like so
I would still recommend just monitoring the hash though.
Simple like that
#hardcore
an example
Another way to do that is to set the url, and use window.location.reload() to force the reload.
<a href="/example#myanchor2"
onclick="setTimeout(location.reload.bind(location), 1)">
</a>
Basically, the setTimeout delays the reload. As there is no return false in the onclick, the href is performed. The url is then changed by the href and only after that is the page reloaded.
No need for jQuery, and it is trivial.
My favorite solution, inspired by another answer is:
myanchor2
href link will not be followed so you can use your own preference, for example: "" or "#".
Even though I like the accepted answer I find this more elegant as it doesn't introduce a foreign parameter. And both #Qwerty's and #Stilltorik's answers were causing the hash to disappear after reload for me.
What's the point of using client-side JS if you're going to keep reloading the page all the time anyways? It might be a better idea to monitor the hash for changes even when the page is not reloading.
This page has a hash monitor library and a jQuery plugin to go with it.
If you really want to reload the page, why not use a query string (?foo) instead of a hash?
Another option that hasn't been mentioned yet is to bind event listeners (using jQuery for example) to the links that you care about (might be all of them, might not be) and get the listener to call whatever function you use.
Edit after comment
For example, you might have this code in your HTML:
example1
example2
example3
Then, you could add the following code to bind and respond to the links:
<script type="text/javascript">
$('a.myHash').click(function(e) {
e.preventDefault(); // Prevent the browser from handling the link normally, this stops the page from jumping around. Remove this line if you do want it to jump to the anchor as normal.
var linkHref = $(this).attr('href'); // Grab the URL from the link
if (linkHref.indexOf("#") != -1) { // Check that there's a # character
var hash = linkHref.substr(linkHref.indexOf("#") + 1); // Assign the hash to a variable (it will contain "myanchor1" etc
myFunctionThatDoesStuffWithTheHash(hash); // Call whatever javascript you use when the page loads and pass the hash to it
alert(hash); // Just for fun.
}
});
</script>
Note that I'm using the jQuery class selector to select the links I want to 'monitor', but you can use whatever selector you want.
Depending on how your existing code works, you may need to either modify how/what you pass to it (perhaps you will need to build a full URL including the new hash and pass that across - eg. http://www.example.com/example#myanchor1), or modify the existing code to accept what you pass to it from you new code.
Here's something like what I did (where "anc" isn't used for anything else):
And onload:
window.onload = function() {
var hash = document.location.hash.substring(1);
if (hash.length == 0) {
var anc = getURLParameter("anc");
if (anc != null) {
hash = document.location.hash = anc;
}
}
}
The getURLParameter function is from here
If you need to reload the page using the same anchor and expect the browser to return to that anchor, it won't. It will return to the user's previous scroll position.
Setting a random anchor, overwriting it and then reloading seems to fix it. Not entirely sure why.
var hash = window.location.hash;
window.location.hash = Math.random();
window.location.hash = hash;
window.location.reload();
Try this its help for me
<a onclick="location.href='link.html'">click me</a>
In your anchor tag instead of
click me
As suggested in another answer, monitoring the hash is also an option. I ended up solving it like this so it required minimal code changes. If I had asked the original question, I believe I would have loved to see this option fully explained.
The added benefit is that it allows for additional code for either of the situations (hash changed or page loaded). It also allows you to call the hash change code manually with a custom hash. I used jQuery because it makes the hash change detection a piece of cake.
Here goes!
Move all the code that fires when a hash is detected into a separate independent function:
function openHash(hash) {
// hashy code goes here
return false; // optional: prevents triggering href for onclick calls
}
Then detect your hash for both scenarios like so:
// page load
$(function () {
if(typeof location.hash != typeof undefined) {
// here you can add additional code to trigger only on page load
openHash(location.hash);
}
});
// hash change
$(window).on('hashchange', function() {
// here you can add additional code to trigger only on hash change
openHash(location.hash);
});
And you can also call the code manually now like
Magic
Hope this helps anyone!
Try this by adding simple question mark:
Going to Anchor2 with Refresh

Categories