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

123
Views
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 answers
Answer question

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 Report
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!