1

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)

shinzou
  • 5,850
  • 10
  • 60
  • 124
  • Hide whole page using css and display the page if the cookie is not valid. – Sa Si Kumar Oct 20 '16 at 13:10
  • When the browser encounters a script tag when parsing the HTML, it stops parsing and hands over to the Javascript interpreter. [http://stackoverflow.com/a/2920207/4045532](http://stackoverflow.com/a/2920207/4045532). Your issue is because it's an ajax call, so you see the page render before the data returns. I would hide the existing page content as @Sasikumar mentioned and then render once the ajax request completes, or show the existing data in js when you want to. – Corporalis Oct 20 '16 at 13:12

1 Answers1

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();
   }
Atal Kishore
  • 4,480
  • 3
  • 18
  • 27