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 firs开发者_如何学运维t 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 head
tag. 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)
Another option is to keep the table hidden, then making it visible as the last statement in your $(document).Ready().
JavaScript is usually kept at the bottom of the page, in order to let your page display basic style and content before JS processing begins.
If the content of the table needs to be displayed correctly before JS runs, the only real option is to serve it with appropriate sorting + styling, rather than depend on JS doing it for you. I would suggest doing this anyhow.
精彩评论