To preface, I have looked at the existing posts about this issue on SO and I believe my code incorporates all suggested fixes, yet it still doesn't work.
I am trying to get a simple onload event to fire:
var test = function() {
console.log("Script loaded! V2")
}
//Append new user script to head
const userProg = document.createElement('script')
userProg.type = 'text/javascript'
userProg.id = 'user-program'
userProg.addEventListener('load', test, false)
userProg.onload = function() {
console.log("Script loaded! V1")
}
userProg.text = [goatPuzzleSetupCode, genericSetupCode, userCode, resultToJSONCode].join('\n')
document.head.appendChild(userProg)
What's frustrating is that I have gotten the onload event to fire before, but I don't have a copy of my code from when it was working. So I'm not sure what the issue is.
It sounds like you're looking for an event like afterscriptexecute, which is unfortunately non-standard and shouldn't be used. But, because you're inserting the script text directly already, it should be simple enough to add something else to the text that fires a window function, assuming the appended script doesn't contain errors. For example:
window.scriptLoaded = function() {
console.log("Script loaded! V2")
}
const text1 = 'console.log("script1 running")';
const text2 = 'console.log("script2 running")';
//Append new user script to head
const userProg = document.createElement('script')
userProg.text = [text1, text2, 'scriptLoaded();'].join('\n');
document.head.appendChild(userProg)
(onload doesn't work because, as a comment said:
The onload is for when the element loads. i,e finished downloading.
but there's nothing for a script without a src to download)
Onload is not working in your case because there is nothing to load for an inline script It will work for the scripts that will be downloaded i.e. remote scripts.
However also need to take care about 1 thing for remote scripts:
Need to set the src attribute after the onload event.
//Append new user script to head
var goatPuzzleSetupCode= console.log("Script goatPuzzleSetupCode");
var genericSetupCode= console.log("Script genericSetupCode");
var userCode= console.log("Script userCode");
var resultToJSONCode= console.log("Script resultToJSONCode");
var userProg = document.createElement('script');
var script="//cdnjs.cloudflare.com/ajax/libs/less.js/1.3.3/less.min.js";
//userProg.addEventListener('load', test, false);
userProg.onload = function(script) {
console.log("Script loaded! 1"+script)
test();
};
userProg.src=script;
userProg.text = [goatPuzzleSetupCode, genericSetupCode, userCode, resultToJSONCode].join('\n')
document.head.appendChild(userProg);
var test = function() {
console.log("Script loaded! 2")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With