I'm making a web application based on Express and axios. I'm trying to create a static navigation and load an HTML file on each menu click while dynamically loading the associated script file.
...
router.get('/page/home/:location', (req, res) => {
const location = req.params.location;
fs.readFile(path.resolve(__dirname + `../../../views/pages/${location}.ejs`), (error, html) => {
if(error) {
res.status(500).end();
} else {
res.status(200).end(html);
}
});
});
...
<button class="nav-grid-item-menu-button" type="button" onclick="mainSidebarUiMouseclick(this)" value="diary">Diary</button>
...
<div id="content"></div>
const mainSidebarUiMouseclick = (event) => {
const content = document.getElementById('content');
let script;
// Remove all child
content.innerHTML = '';
axios.get(`${window.location.href}/${event.value}`)
.then((res) => {
content.innerHTML = res.data;
})
.then(() => {
switch(event.value) {
case 'diary':
script = document.createElement('script');
script.setAttribute('src', `/js/pages/ui-${event.value}-controller.mjs`);
script.setAttribute('crossorigin', 'anonymous');
script.setAttribute('type', 'module');
script.defer = true;
script.addEventListener('load', () => {
console.info(`@system, Dynamic script loading complete`);
});
content.appendChild(script);
break;
...
}
})
.catch((error) => { console.error(`@error, ${error}`); });
};
The script is always executed the first time it is clicked without any problem. However, if you return to another menu after moving to another menu, the script is not executed normally. This structure is not available for document.body. The reason is that all existing script files are dynamically erased when the menu is clicked. How should I solve it?