Window.onload is randomly emitted or not

window.onload is randomly emitted or not

Hello. I have content-script that adds some html onto page when it is loaded. It worked fine on all websites where content-scripts are allowed but now I made new version of my addon. Now websites forget to emit window.onload event sometimes. However I always get print in console written with console.log() placed outside of any functions in the same js file. If I disable new version and go to previous, the problem disappears. What could happen?

Here is new version and previous version of code.

Content scripts are by default injected when the document is idle. This is equivalent to listening for the load event. Crucially, this means that the event may have already been emitted, and I don’t think load is re-emitted when you attach a listener if it has already happened. In conclusion you should likely be able to not have a load listener at all, as long as you keep the run_at setting at the default value of document_idle.

Docs: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/content_scripts#run_at

Sounds good, I will try. But why it works for older version? Did some defaults changed?
I also noticed mentioned console.log() was printed twice. Can content-scripts be loaded many times?

The load event happens when document.readyState changes; content scripts with run_at = document_idle are not executed before it changes. I.e. I don’t think anybody bothered to define an exact order of things there.

Can content-scripts be loaded many times?

Yes, if you insert it multiple times. Also the page could have frames in which the script (depending on its settings) may be inserted as well, resulting in multiple prints.