Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

223
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda