onload event on script object sometimes not triggered

Ask for help about NoScript, no registration needed to post
Johannes

onload event on script object sometimes not triggered

Post by Johannes »

Site to reproduce: https://openmpt.org/screenshots (I maintain this site and all scripts from the site are allowed in NoScript)

This is something that I'm sure used to work just fine with NoScript, but I don't know when exactly it might have broken.
This website loads a JavaScript files with the async attribute (screenshots.min.js) and applies an onload function as soon as the script has finished loading asynchronously. Now if I hit Ctrl+Shift+R in Firefox to force-reload the site, the onload event is never fired (I verified by adding a console.log in the onload handler). If I visit this site by clicking a link from another site instead, or just hitting F5, the onload handler is usually called and the script executes. Disabling NoScript avoids the issue so I'm pretty sure it is caused by NoScript.
Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:96.0) Gecko/20100101 Firefox/96.0
User avatar
Giorgio Maone
Site Admin
Posts: 9524
Joined: Wed Mar 18, 2009 11:22 pm
Location: Palermo - Italy
Contact:

Re: onload event on script object sometimes not triggered

Post by Giorgio Maone »

My suspicion: since you attach the onload event handler programmatically, after the script element has already been parsed, there's no guarantee the script has not been loaded yet (async means it doesn't block the page parsing, not that it's necessarily executed later - that's "defer"), and therefore the listener may or may not be called in the end.

NoScript's presence may exacerbate this phenomenon, but it's not its root cause.

In order to fix this, you can either use the onload HTML attribute in the script element itself:

Code: Select all

<script src="https://openmpt.org/baguettebox/screenshots.min.js?d4d78e6b" async id="lightboxJS" onload="initBaguetteBox()"></script>
or add a document-level listener very early (before the lightboxJS script):

Code: Select all

document.addEventListener("load", e => { if (e.target.id === "lightboxJS") initBaguetteBox(); });
Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:97.0) Gecko/20100101 Firefox/97.0
Johannes

Re: onload event on script object sometimes not triggered

Post by Johannes »

Thanks Giorgio, I wasn't aware that onload cannot be fired retroactively. I'll look into the proposed alternatives.
Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:96.0) Gecko/20100101 Firefox/96.0
Post Reply