Search code examples
javascriptonloadscript-tag

onload event in script tag not firing


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.


Solution

  • 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)