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

126
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
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