Day 005 - Let's get ready to jQuery
Let's head over to the H5BP index.html.
Notice all the script tags are at the bottom? So, why is this?
When a page is rendered you'll be able to view the source of that page. The code generated is the Document Object Model often referred to as the DOM
.
When you're loading a page this code is rendered from top to bottom. If we were to render the page in slo-mo and we had all the script tags at the top the DOM would have to effectively stop whilst it grabs all the code from the scripts. Whilst it's doing this the user will be looking at a blank screen, not good. So to improve the perceived page load time it's worth keeping scripts at the bottom.
However, there may be instances where you need to include a script file at the top of the DOM or where other JavaScript code is being called from a difference source, but doing this will then mean that the script isn't aware of the code that's below it as the JavaScript has already been executed.
This is where $(document).ready()
comes to use and will ensure that the code will only execute when the DOM is ready. The examples in Day 004 take advantage of $(document).ready()
and also show an alternative way of writing this code.
Here's a handy snippet using the alternative way for Sublime Text 2:
# Self Invoking Anonymous Function Snippet for Sublime Text 2:
<snippet>
<content><![CDATA[(function() \{
$0
\})();]]></content>
<tabTrigger>siaf</tabTrigger>
<scope>source.js,source.js.embedded.html</scope>
<description>Self Invoking Anonymous Function</description>
</snippet>
Not sure what Sublime Text 2 or a snippet is? Fear not! Head on over to Day 006.