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>
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.