I'd like to know how $(document).ready()
works, along with scripts in general. Say I have scripts that are at the bottom of the page (for performance reasons I'm told?). As an example: say you have a link and you need to prevent it's default action (preventDefault()
). If the script is at the bottom of the page, isn't it possible that the user can see the page and click the link before the browser knows not to follow the link?
Scripts in the 'head' section are evaluated at the point where the script tag is loaded into the browser (i.e. before the body). Script tags at the end of the document are also executed when they are encountered by the browser as it parses the page - so before the 'document ready' event. The 'document ready' event is fired when the whole page is loaded - i.e. when the browser parses the '</html>'
closing tag.
So yes, if it takes a while to load and execute a script that disables links at the end of the document, the user could click a link in the mean time.
One option is to operate in reverse - i.e. load the page with links disabled, and have your javascript enable them. Or, use 'live' or 'delegate' in scripts at the top (after jquery is loaded) so that links are affected as they are created.
Look here for some complexities regarding how browsers handle dynamically loaded scripts slightly differently.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With