问题描述
我有一个脚本,我想在页面开始加载之前运行。该脚本检查变量的值,并根据值将用户重定向到新页面。
I have a script that I want to run before the page start to load. The script checks the value of a variable and depending on the value redirect the user to a new page.
我可以成功检查变量并在需要时重定向但页面仍然加载并显示空白页面,然后快速重定向到另一页面。我不希望在重定向之前在页面上显示该空页面。
I can successfully check the variable and redirect if needed but the page still loads and display empty page but then quickly redirects to the other page. I don't want that empty page to be displayed on the page at all before the redirect.
谢谢你,
Ver
Thank you,Ver
推荐答案
<head>
<script>
if(condition){
window.location = "http://yournewlocation.com";
}
</script>
</head>
<body>
...
</body>
这将强制在页面呈现任何内容之前检查条件和url位置的更改。值得注意的是,在调用jQuery库之前,你将特别想要这样做,这样你就可以避免所有的库加载。有些人可能会争辩说,这会更好地放在一个包装器方法中,所以这里调用的方法是:
This will force the checking of condition and the change in url location before the page renders anything. It is worth noting that you will specifically want to do this before the call to the jQuery library so you can avoid all that library loading. Some might also argue that this would be better placed in a wrapper method and called so here is that method:
function redirectHandler(condition, url){
if(condition){
window.location = url;
}else{
return false;
}
}
这将允许您检查多个条件并重定向到基于它的不同位置:
That would allow you to check multiple conditions and redirect to different locations based on it:
if(redirectHandler(nologgedin, "/login.php")||redirectHandler(adminuser, "/admin.php"));
或者如果你只需要它只运行一次,但你喜欢在全球范围内什么也没有命名空间:
or if you only need it to run once and only once, but you like having nothing in the global namespace:
(function(condition, url){
if(condition)window.location=url;
})(!loggedin, "/login.asp");
这篇关于如何在页面开始加载之前运行jQuery或JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!