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

170
Visualizações
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 à 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