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

127
Vistas
How load script tag as DOM element and run as if it was placed in head tag

I'm looking for a way in the purpose to speed up site loading and postpone non-urgent scripts. I need to load a script on button click as it placed in Head tag <script ...>.

async function do_script_load() {
    var script = document.createElement("script");
    script.src = "https://web.webformscr.com/apps/fc3/build/loader.js";
    script.type = "text/javascript";
    script.setAttribute("async", "");
    await item.parentElement.querySelector(".n-bell-bubble").appendChild(script); 
    
    do_other_stuff();
 }

addEventListener( "click" , () => {
    do_script_load()
})

The problem is that the script get loaded but it is not being started. I'm looking for a way to run the script as a script added as used to.

<head>
    <script src="..." async></script>
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The script you are loading is listening for the window's load event to execute.
(from https://web.webformscr.com/apps/fc3/build/loader.js)

window.addEventListener("load",e,!1)

This event is long fired when you do append the script, and hence it will wait for something that already did happen.
You can quick-fix this by adding a load event handler on your <script>and fire a new load event on the window when this happens:

script.addEventListener("load", e => window.dispatEvent(new Event("load")));

Though it seems we need some other elements in the page with sp-form-id attributes that I don't know of and thus couldn't test myself.

But if you can reach to the author of this script you load, then you should ask them to expose a method to initialize it without having to fire this event, since other parts of your page may very well rely on the fact that this event is only supposed to fire once.


Also note that you may want to pass a { once: true } option to your click listener to avoid loading this script every time the user clicks.

about 4 years ago · Juan Pablo Isaza Denunciar
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