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

171
Vistas
Loading HTML snippet containing <script> and appending to <head> does not execute the script

In a DOMContentLoaded callback an HTML snippet is fetch()ed from the server which contains a <script src="..."> tag among other things, e.g. a CSS link element. This snippet is first wrapped into a freshly created div with div.innerHTML = snippet and then added to the head element with

document.head.append(...div.childNodes)

As a result we have:

  • All elements from the snippet are in the head just right as can be seen with the browser's developer tools.
  • The CSS gets applied to the page.
  • But: the script is not even loaded as can be seen in the network tab of the browser's developer tools.

Question: why is the script not loaded and executed? Is this some security measure? A way to get the script executed is to this:

  document.head.querySelectorAll('script').forEach((scriptEl) => {
    const newScriptEl = document.createElement('script');
    scriptEl.getAttributeNames().forEach((name) => {
      newScriptEl[name] = scriptEl.getAttribute(name);
    });
    scriptEl.replaceWith(newScriptEl);
  });

i.e. script elements freshly created and replaced into the head do the trick. Interestingly scriptEl.replaceWith(scriptEl.cloneNode(true)) does not work. Is it possible to load the snippet and add it to head such that the script tag scripts are executed without this extra step?

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