Search code examples
javascripthttp-redirectlocation-href

Strange JavaScript behaviour with window.location.href and program flow


I have an index site which checks if a cookie exists and if it has the value EN. If so it should redirect to an English index.shtml. Otherwise or if there is no (English) cookie, it should redirect to the German next page:

if (document.cookie)  {
    var cookieValue = document.cookie;
    if (cookieValue.indexOf("MYCOOKIE=EN") > -1)  {
        window.location.href="en/index.shtml";
    }
}
window.location.href="kategorien/hauptkategorie.shtml";

Now something very strange happens: The English cookie exists (I checked cookieValue with JavaScript alert and it shows EN), but even though the href inside the if won't be executed but the 2nd href will be executed. Why is this so?

When I add 2 elses, it works like expected:

if (document.cookie)  {
     var cookieValue = document.cookie;
     if (cookieValue.indexOf("MYCOOKIE=EN") > -1)  {
         window.location.href="en/index.shtml";
     }
     else  {
         window.location.href="kategorien/hauptkategorie.shtml";
     }
}
else  {
     window.location.href="kategorien/hauptkategorie.shtml";
}

Why is this so that it redirects to hauptkategorie.shtml if I leave the elses?


Solution

  • You have a normal Javascript statement after the if.

    There is nothing telling that statement not to run, unless you put it in an else.

    Navigating to a new page does not terminate execution of the current page until the new page actually loads.