如何在页面加载之前使JS页面重定向触发器 [英] How to make JS page redirect trigger before page load
本文介绍了如何在页面加载之前使JS页面重定向触发器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用以下脚本在第一次访问时将页面的访问者重定向到另一个页面,但是它将首先加载index.html页面,然后触发重定向.谁能指出我在页面加载之前如何触发此脚本的方向?
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>
(此处使用的JS代码段摘自堆栈溢出:首次访问时JS重定向到启动页面)
(the JS snippet used here was taken from Stack Overflow: JS to redirect to a splash page on first visit)
谢谢.
推荐答案
在加载窗口时无需等待:
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>
Petr B.也说对了:在您的情况下,服务器端重定向会更好.
Also Petr B. said right thing: server-side redirect is better in your case.
这篇关于如何在页面加载之前使JS页面重定向触发器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文