103

I would like to implement a JavaScript code which states this: if the page is loaded completely, refresh the page immediately, but only once. I'm stuck at the "only once":

window.onload = function () {window.location.reload()}

this gives a loop without the "only once". jQuery is loaded if this helps.

Carol-Theodor Pelu
  • 906
  • 2
  • 10
  • 26
Martin
  • 1,031
  • 2
  • 8
  • 3
  • 1
    What are you accomplishing by reloading the page? There may be a better way to solve the problem. – FishBasketGordo Aug 08 '11 at 16:46
  • there is a jquery fullscreen gallery script starting on the page, but the thumbs are never loaded completely. if you hit the "refresh" button for the page it just loads the remaining ones... so it's clear that I'm searching for some kind of workaround... giving the thumbs seperately is too complicated (CMS), other bugfixes didn't really help... It's 4 MB of images, approx. 300kb each, at some point the thumbs of the images are not resized and displayed anymore (timeout? too much, too big??) but the page finishes loading. – Martin Aug 08 '11 at 16:52
  • I have experienced a similar problem (javascripts not working) when using pjax http://pjax.heroku.com/. – Pratik Khadloya Jan 07 '12 at 21:30

20 Answers20

116

I'd say use hash, like this:

window.onload = function() {
    if(!window.location.hash) {
        window.location = window.location + '#loaded';
        window.location.reload();
    }
}
Cokegod
  • 8,256
  • 10
  • 29
  • 47
78

When I meet this problem, I search to here but most of answers are trying to modify existing url. Here is another answer which works for me using localStorage.

<script type='text/javascript'>

(function()
{
  if( window.localStorage )
  {
    if( !localStorage.getItem('firstLoad') )
    {
      localStorage['firstLoad'] = true;
      window.location.reload();
    }  
    else
      localStorage.removeItem('firstLoad');
  }
})();

</script>
Haimei
  • 12,577
  • 3
  • 50
  • 36
31
<script type="text/javascript">
$(document).ready(function(){    
    //Check if the current URL contains '#'
    if(document.URL.indexOf("#")==-1){
        // Set the URL to whatever it was plus "#".
        url = document.URL+"#";
        location = "#";

        //Reload the page
        location.reload(true);
    }
});
</script>

Due to the if condition the page will reload only once.I faced this problem too and when I search ,I found this nice solution. This works for me fine.

Thusitha Sumanadasa
  • 1,669
  • 2
  • 22
  • 30
14

Check this Link it contains a java-script code that you can use to refresh your page only once

http://www.hotscripts.com/forums/javascript/4460-how-do-i-have-page-automatically-refesh-only-once.html

There are more than one way to refresh your page:

solution1:

To refresh a page once each time it opens use:

<head>
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Expires" CONTENT="-1">
</head>

sollution2:

<script language=" JavaScript" >
<!-- 
function LoadOnce() 
{ 
window.location.reload(); 
} 
//-->
</script>

Then change your to say

<Body onLoad=" LoadOnce()" >

solution3:

response.setIntHeader("Refresh", 1);

But this solution will refresh the page more than one time depend on the time you specifying

I hope that will help you

Areeg Samir
  • 577
  • 5
  • 6
6
<script>

function reloadIt() {
    if (window.location.href.substr(-2) !== "?r") {
        window.location = window.location.href + "?r";
    }
}

setTimeout('reloadIt()', 1000)();

</script>

this works perfectly

Godwin Tommy
  • 71
  • 1
  • 4
4

Finally, I got a solution for reloading page once after two months research.

It works fine on my clientside JS project.

I wrote a function that below reloading page only once.

1) First getting browser domloading time

2) Get current timestamp

3) Browser domloading time + 10 seconds

4) If Browser domloading time + 10 seconds bigger than current now timestamp then page is able to be refreshed via "reloadPage();"

But if it's not bigger than 10 seconds that means page is just reloaded thus It will not be reloaded repeatedly.

5) Therefore if you call "reloadPage();" function in somewhere in your js file page will only be reloaded once.

Hope that helps somebody

// Reload Page Function //
                function reloadPage() {
                    var currentDocumentTimestamp = new Date(performance.timing.domLoading).getTime();
                    // Current Time //
                    var now = Date.now();
                    // Total Process Lenght as Minutes //
                    var tenSec = 10 * 1000;
                    // End Time of Process //
                    var plusTenSec = currentDocumentTimestamp + tenSec;
                    if (now > plusTenSec) {
                        location.reload();
                    }
                }


                // You can call it in somewhere //
                reloadPage();
3

i put this inside my head tags of the page i want a single reload on:

<?php if(!isset($_GET['mc'])) {
echo '<meta http-equiv="refresh" content= "0;URL=?mc=mobile" />';
} ?>

the value "mc" can be set to whatever you want, but both must match in the 2 lines. and the "=mobile" can be "=anythingyouwant" it just needs a value to stop the refresh.

mike
  • 35
  • 3
3

Use window.localStorage... like this:

var refresh = window.localStorage.getItem('refresh');
console.log(refresh);
if (refresh===null){
    window.location.reload();
    window.localStorage.setItem('refresh', "1");
}

It works for me.

Alexander Wigmore
  • 3,157
  • 4
  • 38
  • 60
1

After </body> tag:

<script type="text/javascript">
if (location.href.indexOf('reload')==-1)
{
   location.href=location.href+'?reload';
}
</script>
1

You can make one verable once = false then reload your page with if else like if once == false reload page an make once true.

1

I got the Answer from here and modified it.This is the perfect solution for me.

var refresh = window.localStorage.getItem('refresh');
console.log(refresh);
setTimeout(function() {
if (refresh===null){
    window.location.reload();
    window.localStorage.setItem('refresh', "1");
}
}, 1500); // 1500 milliseconds = 1.5 seconds

setTimeout(function() {
localStorage.removeItem('refresh')
}, 1700); // 1700 milliseconds = 1.7 seconds
MOHAMMAD ZEESHAN
  • 273
  • 3
  • 15
0

Try with this

var element = document.getElementById('position');        
element.scrollIntoView(true);`
kleopatra
  • 51,061
  • 28
  • 99
  • 211
0

Please try with the code below

var windowWidth = $(window).width();

$(window).resize(function() {
    if(windowWidth != $(window).width()){
    location.reload();

    return;
    }
});
0

Here is another solution with setTimeout, not perfect, but it works:

It requires a parameter in the current url, so just image the current url looks like this:

www.google.com?time=1

The following code make the page reload just once:

 // Reload Page Function //
    // get the time parameter //
        let parameter = new URLSearchParams(window.location.search);
          let time = parameter.get("time");
          console.log(time)//1
          let timeId;
          if (time == 1) {
    // reload the page after 0 ms //
           timeId = setTimeout(() => {
            window.location.reload();//
           }, 0);
   // change the time parameter to 0 //
           let currentUrl = new URL(window.location.href);
           let param = new URLSearchParams(currentUrl.search);
           param.set("time", 0);
   // replace the time parameter in url to 0; now it is 0 not 1 //
           window.history.replaceState({}, "", `${currentUrl.pathname}?${param}`);
        // cancel the setTimeout function after 0 ms //
           let currentTime = Date.now();
           if (Date.now() - currentTime > 0) {
            clearTimeout(timeId);
           }
          }

The accepted answer uses the least amount of code and is easy to understand. I just provided another solution to this.

Hope this helps others.

MING WU
  • 2,962
  • 1
  • 12
  • 16
0

React Hook worked for me.

import { useEffect, useState } from 'react';

  const [load, setLoad] = useState(false);

  window.onload = function pageLoad() {
      if (load) {
        window.location.reload(true);
        setLoad(false);
      }
    };
saint
  • 13
  • 3
0

You'd need to use either GET or POST information. GET would be simplest. Your JS would check the URL, if a certain param wasn't found, it wouldn't just refresh the page, but rather send the user to a "different" url, which would be the same URL but with the GET parameter in it.

For example:
http://example.com -->will refresh
http://example.com?refresh=no -->won't refresh

If you don't want the messy URL, then I'd include some PHP right at the beginning of the body that echos a hidden value that essentitally says whether the necessary POST param for not refreshing the page was included in the initial page request. Right after that, you'd include some JS to check that value and refresh the page WITH that POST information if necessary.

maxedison
  • 17,243
  • 14
  • 67
  • 114
0

nothing work for me perfectly except this, -added to my JavaScript file-:

function LoadOnce() {
if (localStorage.getItem('executed') == 'false') {
window.location.reload()
localStorage.setItem('executed', true)
}
}

setTimeout(function () {
LoadOnce()
}, 100)

and in the previous page I wrote:

localStorage.setItem('executed', false)
-1
        var foo = true;
        if (foo){
            window.location.reload(true);
            foo = false;

        }
Ben Bieler
  • 1,518
  • 1
  • 14
  • 22
-1

use this

<body onload =  "if (location.search.length < 1){window.location.reload()}">
-2

Use rel="external" like below is the example

<li><a href="index.html" rel="external" data-theme="c">Home</a></li>
Jay Bharat
  • 33
  • 3