Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

221
Views
Why is it only executed once when generating dynamic javascript?

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.

Page Router

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

Main(.ejs)

...
<button class="nav-grid-item-menu-button" type="button" onclick="mainSidebarUiMouseclick(this)" value="diary">Diary</button>
...
<div id="content"></div>

Controller

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?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!