matt136 matt136 - 1 month ago 6
Javascript Question

JavaScript window.location.replace(url) Reloading Multiple Times

my aim is to create a script which will redirect the user from the home page to the relevant language page based on their browser language, here is what I have so far:

<script>
jQuery(document).ready(function() {
var language = window.navigator.userLanguage || window.navigator.language;
if (language === "en-US") {
window.location.replace("/test")
}
});
</script>


The issue is that when the
/test
page loads, it will reload several times before finally stopping. Please see below to see this in action (only works if browser language is "en-US")

http://ts564737-container.zoeysite.com/

Could anybody please advise where this is going wrong and why the location is being replaced multiple times? Apologies in advance, I've only just began to learn coding. Thank you for your time.

Answer

Because your code is wrapped in the jQuery(document).ready(function() { each time the page is loaded, your window.location.replace is called and starts the page refresh.

I did notice that you had a language dropdown on your site, so maybe try something similar to this instead:

<select class="foo" id="bar" onchange="dropdownChange()"> //options here </select>

and your javscript to

function dropdownChange() { var dropdown = document.getElementById("bar"); var language = dropdown.options[dropdown.selectedIndex].value; if (language === "en-US") { window.location.replace("/test"); } }