Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

222
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda