I am working with some legacy HTML/JS code, where I need to attach to the load event.
The script I am working with is outside of the <head> tags.
Is listening to the load event unreliable when attaching the event listening outside of the head?
i.e.
Is it somehow possible that the page already loads and ignores my event listener?
In my testing the event listener is fired fine, but I’m ensure if this is the case all the time.
btw.
Due to the legacy nature I need to avoid using jQuery (an unhappy day).
No, not if you’re literally talking about
window.onload.window.onloadhappens very, very late in the process, after the entire HTML has been parsed (and also after any external resources like images and stylesheets and such have been completely loaded). It should be fine.Somewhat off-topic, but you can get an earlier reliable call if you like even without using jQuery. Just put this just before your closing
</body>tag:At that point, the DOM is reliably available, but the call happens a lot earlier than
window.onload(depending on the size of your external resources, possibly even seconds earlier). Google’s JavaScript experts argue against the need for a jQuery-style “ready” event (see the link above) for this very reason. Some “unobtrusive JavaScript” folks don’t like it (although to me it’s not substantially different from putting ascripttag in thehead, provided the function is standardized across your app; it’s not like sprinklingonclickattributes all over the place), but it sounds like that ship has already sailed in the case of this code you’ve inherited. 😉