program story

첫 페이지로드 후 한 번 페이지 새로 고침

inputbox 2020. 10. 21. 08:01
반응형

첫 페이지로드 후 한 번 페이지 새로 고침


페이지가 완전히로드되면 페이지를 즉시 새로 고치지 만 한 번만 표시하는 JavaScript 코드를 구현하고 싶습니다. 나는 "한 번만"에 갇혀있다 :

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

이것은 "한 번만"없이 루프를 제공합니다. 이것이 도움이된다면 jQuery가로드됩니다.


나는 다음과 같이 해시를 사용한다고 말하고 싶습니다.

window.onload = function() {
    if(!window.location.hash) {
        window.location = window.location + '#loaded';
        window.location.reload();
    }
}

이 문제를 만나면 여기로 검색하지만 대부분의 답변은 기존 URL을 수정하려고합니다. 다음은 localStorage를 사용하여 나를 위해 작동하는 또 다른 답변입니다.

<script type='text/javascript'>

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

</script>

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

if 조건으로 인해 페이지가 한 번만 다시로드됩니다.이 문제에 직면했고 검색 할 때이 좋은 해결책을 찾았습니다. 이것은 나를 위해 잘 작동합니다.


이 링크를 확인하면 페이지를 한 번만 새로 고칠 수있는 자바 스크립트 코드가 포함되어 있습니다.

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

페이지를 새로 고치는 방법은 여러 가지가 있습니다.

solution1 :

페이지가 열릴 때마다 페이지를 새로 고치려면 다음을 사용하십시오.

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

해결책 2 :

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

그런 다음 말로 변경

<Body onLoad=" LoadOnce()" >

solution3 :

response.setIntHeader("Refresh", 1);

그러나이 솔루션은 지정한 시간에 따라 페이지를 두 번 이상 새로 고칩니다.

도움이 되길 바랍니다


나는 이것을 하나의 재로드를 원하는 페이지의 내 머리 태그 안에 넣습니다.

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

값 "mc"는 원하는대로 설정할 수 있지만 둘 다 2 줄에서 일치해야합니다. "= mobile"은 "= anythingyouwant"일 수 있으며 새로 고침을 중지하는 값만 있으면됩니다.


</body>태그 :

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

GET 또는 POST 정보를 사용해야합니다. GET이 가장 간단합니다. JS는 URL을 확인합니다. 특정 매개 변수가 발견되지 않으면 페이지를 새로 고치는 것이 아니라 동일한 URL이지만 GET 매개 변수가있는 "다른"URL로 사용자를 보냅니다. .

예 :
http : //example.com- > 새로 고침
http://example.com?refresh=no- > 새로 고침 안함

지저분한 URL을 원하지 않는 경우, 페이지를 새로 고치지 않는 데 필요한 POST 매개 변수가 초기 페이지 요청에 포함되었는지 여부를 본질적으로 나타내는 숨겨진 값을 반영하는 본문 시작 부분에 PHP를 포함합니다. 그 직후에 JS를 포함하여 해당 값을 확인하고 필요한 경우 해당 POST 정보로 페이지를 새로 고칩니다.


이것으로 시도

var element = document.getElementById('position');        
element.scrollIntoView(true);`

아래 코드로 시도하십시오

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

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

    return;
    }
});

        var foo = true;
        if (foo){
            window.location.reload(true);
            foo = false;

        }

이것을 사용하십시오

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

window.localStorage ... 사용하십시오.

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

나를위한 일


마침내 두 달 간의 조사 끝에 한 번 페이지를 다시로드하는 솔루션을 얻었습니다.

내 클라이언트 측 JS 프로젝트에서 잘 작동합니다.

한 번만 페이지를 다시로드하는 기능을 작성했습니다.

1) 먼저 브라우저 domloading 시간 확보

2) 현재 타임 스탬프 얻기

3) 브라우저 domloading 시간 + 10 초

4) 브라우저 domloading 시간 + 현재 타임 스탬프보다 10 초 더 큰 경우 "reloadPage ();"를 통해 페이지를 새로 고칠 수 있습니다.

하지만 10 초 이하이면 페이지가 새로 고침되어 반복적으로 다시로드되지 않음을 의미합니다.

5) 따라서 "reloadPage ();"를 호출하면 js 파일 페이지의 어딘가에있는 함수는 한 번만 다시로드됩니다.

누군가를 돕는 희망

// 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();

setTimeout을 사용하는 또 다른 솔루션은 완벽하지는 않지만 작동합니다.

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.


Use rel="external" like below is the example

<li><a href="index.html" rel="external" data-theme="c">Home</a></li>

참고URL : https://stackoverflow.com/questions/6985507/one-time-page-refresh-after-first-page-load

반응형