Fast redirect when loading a page

时间:2016-10-20 13:01:47

标签: javascript html ajax tomcat web

I want to redirect the user from the login page to an inner page if he has certain cookies, I placed a script at the top of the page, but I still see the login page for a split second.

Is there a way to make it faster or pause loading the rest of the DOM so the page won't appear if it's going to redirect?

<html>
<script src="script/jquery-3.1.1.min.js"></script>
<script src="script/js.cookie.js"></script>
<script>
(function () {
    if (Cookies.get("username")) {
        $.ajax({
            data: {
                "username": Cookies.get("username"),
            },
            url: "login",
            success: function (response) {
                document.open();
                document.write(response);
                document.close();
            }
        });
    }
}());

Alternatively, is there a way to make it send those cookies in the first request for the server? i.e. when the user requests the root url of the site. (I'm using Tomcat)

1 个答案:

答案 0 :(得分:4)

Keep th whole page hidden initially somethig like

<div id="login" style="display:hidden">....</div>

and in code if cookie is not present dispaly the page else redirect without showing the login form

(function () {
    if (Cookies.get("username")) {
        $.ajax({
            data: {
                "username": Cookies.get("username"),
            },
            url: "login",
            success: function (response) {
                document.open();
                $("#login").hide();
                document.write(response);
                document.close();
            }
        });
    }
   else
   {
     $("#login").show();
   }