Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript/jquery - $(document).ready() and script locations

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?

like image 626
Matthew Avatar asked Jul 29 '10 02:07

Matthew


1 Answers

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.

like image 65
sje397 Avatar answered Sep 28 '22 23:09

sje397