javascript 如何在页面加载前触发 JS 页面重定向

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17420694/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 08:15:18  来源:igfitidea点击:

How to make JS page redirect trigger before page load

javascriptredirectcookiesonload

提问by jasonbradberry

I am using the following script to redirect visitors of a page to another page on first visit, however it loads the index.html page first, and then triggers the redirect. Can anyone point me in the direction of how I might trigger this script before the page loads?

我使用以下脚本在第一次访问时将页面的访问者重定向到另一个页面,但是它首先加载 index.html 页面,然后触发重定向。谁能指出我如何在页面加载之前触发此脚本的方向?

<script type="text/javascript">
    function redirect(){
    var thecookie = readCookie('doRedirect');
    if(!thecookie){window.location = '/coming-soon.html';
    }}
    function createCookie(name,value,days){if (days){
    var date = new Date();date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";document.cookie = name+"="+value+expires+"; path=/";
    }
    function readCookie(name){
    var nameEQ = name + "=";var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++){
    var c = ca[i];while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);}
    return null;
    }
    window.onload = function(){redirect();createCookie('doRedirect','true','1');}
</script>

(the JS snippet used here was taken from Stack Overflow: JS to redirect to a splash page on first visit)

(此处使用的 JS 片段取自Stack Overflow: JS to redirect to a splash page on first visit

Thanks.

谢谢。

回答by Tommi

You don't need to wait while window is loaded:

加载窗口时您无需等待:

<script type="text/javascript">
    var thecookie = readCookie('doRedirect');
    if(!thecookie) {
       createCookie('doRedirect','true','1');
       window.location = '/coming-soon.html';
    };
    function createCookie(name,value,days){
      // do work
    }
    function readCookie(name){
      // do work
    }
</script>

Also Petr B. said right thing: server-side redirect is better in your case.

Petr B. 也说对了:在您的情况下,服务器端重定向更好。

回答by Petr B.

Try this How to Run a jQuery or JavaScript Before Page Start to Load.

试试这个如何在页面开始加载之前运行 jQuery 或 JavaScript

Btw. if you want redirect without displaying page you must use php with cookies check.

顺便提一句。如果你想重定向而不显示页面,你必须使用 php 和 cookie 检查。