I’m creating a dynamic content loader with a menu for navigating between sections. Each tab loads its corresponding HTML and JavaScript file. However, I’m encountering redeclaration errors with variables in the JS files when switching tabs. when i try to go again in a section i was before i get this error
Uncaught SyntaxError: Identifier ‘parcours’ has already been declared (at script.js:1:1)”.
How can I dynamically load and unload these scripts without conflicts?
the main html
<body>
<!-- MENU -->
<div id="menuConteneur">
<div class="menuIcon on" id="etudeTravail" onclick="loadContent('etudeTravail/etudeTravail.html', 'etudeTravail/script.js')"></div>
<div class="menuIcon off" id="projets" onclick="loadContent('projets/projets.html', 'projets/script.js')"></div>
<div class="menuIcon off" id="about" onclick="loadContent('about/about.html', 'about/script.js')"></div>
</div>
<!-- DIV CONTENUE DYNAMIQUE -->
<div id="contenu"></div>
<script src="script.js" defer></script>
</body>
the main script :
let lastScript = null;
function loadScript(scriptUrl) {
if (lastScript) {
document.body.removeChild(lastScript);
}
const script = document.createElement('script');
script.src = scriptUrl;
script.defer = true;
document.body.appendChild(script);
lastScript = script;
}
function loadContent(page, scriptUrl) {
const xhr = new XMLHttpRequest();
xhr.open('GET', page, true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
document.getElementById('contenu').innerHTML = xhr.responseText;
if (scriptUrl) {
loadScript(scriptUrl);
}
}
};
xhr.send();
}
loadContent('etudeTravail/etudeTravail.html', 'etudeTravail/script.js');
one of the js
let parcours = document.querySelectorAll(".parcour");
parcours.forEach(parcour => {
parcour.addEventListener("mouseover", function () {
console.log("test2");
})
});
console.log("test");
his html
<div class="parcour">1</div>
<div class="parcour">2</div>
<div class="parcour">3</div>
I’ve implemented a dynamic content loader with a menu that switches between sections by loading different HTML and JavaScript files. I expected the scripts to load and unload without errors. However, I’m facing redeclaration issues with variables when switching tabs. What solutions can help resolve this?