window load event outside of HTML head
I am working with some 开发者_如何学Golegacy 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).
Is listening to the load event unreliable when attaching the event listening outside of the head
No, not if you're literally talking about window.onload
. window.onload
happens 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:
<script type='text/javascript'>
myLoadFunction();
</script>
</body>
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 a script
tag in the head
, provided the function is standardized across your app; it's not like sprinkling onclick
attributes all over the place), but it sounds like that ship has already sailed in the case of this code you've inherited. ;-)
精彩评论