How to make JS page redirect trigger before page load

亡梦爱人 提交于 2019-12-01 12:36:39

问题


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?

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

Thanks.


回答1:


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.




回答2:


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

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



来源:https://stackoverflow.com/questions/17420694/how-to-make-js-page-redirect-trigger-before-page-load

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!