gurinatto
gurinatto

Reputation: 37

How can i run JavaScript inside my webpage only once?

So I am trying to implement an auto language changer for my webpage. But it keeps refreshing the page as it keeps running. I want to run this script only once so it doesn't refresh my page forever.

I have this script:

var language = navigator.language || navigator.userLanguage;

language = language.substring( 0, 2 );

if  (language == "pt" || "pt-BR" || "pt-PT"){
window.location.href = "index.html";
}

else {
window.location.href = "indexEN.html";  //
}

And its called by:

        <!-- Auto Language -->
        <script src="js/language.js"></script>

Upvotes: 0

Views: 181

Answers (3)

Zac Anger
Zac Anger

Reputation: 7747

Think about it as if you have an infinite loop, like while (true) {} — what you need to do is break out of the loop at some point. To break out of this loop, you need to add a check to make sure you're not already on the intended page. That will stop the constant redirection.

var language = navigator.language || navigator.userLanguage

language = language.substring(0, 2)

var ptPage = 'index.html'
var enPage = 'indexEN.html'
// you're calling substring, so no need to check the variants
// your check was also incorrect :)
if (language == "pt") {
  if (window.location.pathname !== '/' + ptPage) {
    window.location.href = ptPage
  }
} else if (window.location.pathname !== '/' + enPage) {
  window.location.href = enPage
}

Upvotes: 1

Rostyk
Rostyk

Reputation: 1159

Don't know if it is a best practice but you can use localStorage.

if((localStorage.getItem('pageLoaded') ?? 'true') === 'true') {
   alert('dsds')
   localStorage.setItem('pageLoaded', 'false')
}

The alert will be executed once

Upvotes: 0

Love2Code
Love2Code

Reputation: 470

Refreshing the page is part of your code, as you can see here

var language = navigator.language || navigator.userLanguage;// get users default language

language = language.substring( 0, 2 );

if  (language == "pt" || "pt-BR" || "pt-PT"){
window.location.href = "index.html";
}
else {
window.location.href = "indexEN.html";  //loading another html file for users who use english
}

So since you are reloading another html file, your javascript IS going to run again. A solution to this would be to make your webpage a SPA (single page application). That way you wouldn't have to reload anything (including javascript). You can also change page content and headers without actually loading a new file. SPA's are usually done in react (with react routing) but you can make then vanilla JS too. https://medium.com/altcampus/implementing-simple-spa-routing-using-vanilla-javascript-53abe399bf3c

Upvotes: 0

Related Questions