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

169
Views
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
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!