JS code should execute only once?

window.addEventListener('load', (event) => {
  var allSectionArticle = document.querySelectorAll("article.commonclass");
	for (let i = 0 ; i < allSectionArticleNumber; i++) { 
		allSectionArticle[i].classList.remove("holidayclass");
	}
});

Is there a way to ensure that a certain code in Javascript is executed only once on every page load or page refresh? Does the above guarantees it?

Yup.

If you stick that at the bottom of your HTML, the code inside the load listener will run once, when the whole page has loaded (including resources such as images).

1 Like

The script is already in HTML bottom β†’

Yes the above load event works. It’s not needed though, for all scripts on the page execute only once too. The usual rule of placing your script at the end of the body, just before the </body> tag also does the job, without needing the script to wait for the load event either.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.