matt136 matt136 - 2 months ago 14
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:

jQuery(document).ready(function() {
var language = window.navigator.userLanguage || window.navigator.language;
if (language === "en-US") {

The issue is that when the
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")

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.


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"); } }