I previously asked a question over on Pro Webmasters about putting Javascript at the bottom of the HTML when using jQuery’s $(document).ready(). The answer was that JS has to wait for the entire DOM to load anyway so it makes no difference where the JS code goes.
However, in practice this doesn’t seem to be the case. I’m using a table sorting plugin and when loading a page with the jQuery at the bottom, I first see the unsorted table. Then the JS kicks in, sorts the table and adds arrows to the headers (which changes the table width too). It’s similar to the “FOUC” (Flash of Unstyled Content) that used to happen a lot with CSS.
With jQuery at the top of the page, the page loads with the table sorted and there is no jumping around.
Why does this happen? Is the only solution to keep the JS at the top, regardless?
This is happening because between the document is ‘ready’ once all of the elements have been placed in the DOM but not necessarily once they have all fully loaded. When the library is in the
<head>tag it is loaded before being inserted into the DOM but if it’s in the<body>tag it is still loading when the document is ready.So even though the document becomes ready it still has to fully load the libraries and execute the required code, which seems to take longer than if it’s in the
headtag. In truth: it happens either way, but it’s more noticeable this way.To prevent the discrepancy: style the javascript-free version of the page the same (or as close to the same as possible) as the javascript version.
(view ready() reference)