Quote:
Originally Posted by felgall
Yes the declarations go at the top - both those declared via the JavaScript var statement AND ALL the HTML that the JavaScript code needs to reference - hence the actual JavaScript code ends up immediately before the </body> tag so that all the declarations it needs to reference go above it.
|
you can put them at the top and use the defer and async attribs to achieve the same perceived-performance benefits as a script placed before the closing body tag.
no matter where you place the script, you shouldn't use free-floating code that expects the document or other tags to be a certain way.
if you're not using a loading library, i've found the best performance comes from loading all the script aync, and using a wait pattern around anything with a dependency.
for example:
Code:
<script defer async src="jquery.js" /></script>
<script defer async src="myplugin.js" /></script>
<script defer async src="mycode.js" /></script>
where myplugin would look like:
Code:
(function _wait(){
if(!window.$){ return setTimeout(_wait, 33); } //depends waiter
$.fn.abc=function(){ return String(this); };
}())
and mycode looks like:
Code:
(function _wait(){
if( !window.$ ||
!window.$.fn.abc ||
!(document.body && document.body.firstChild) ||
document.readyState!=="compete" ){
return setTimeout(_wait, 33);
} //depends waiter
alert( $("body").abc() );
}())
the problem with simply putting tags at the bottom witout using defer and async is that with scripts MOST people use, the scripts wait for "document.ready()", which won't fire until ALL the script tags have been loaded and parsed one-at-a-time. by using defer, or a dom-adder, you can fetch all needed resources at once without halting page rendering. by using a controlled execution instead of plain script-body-execution, those pieces can execute in the proper order no matter which ones arrive first. the above sniffing IS a bit more boiler-plate, but it results in 100% perfect control in all browsers along with top-of-the-line performance on all client machines.
admitting, some new desktop browsers bend the rules and fetch scripts before they are needed according to the 1995 model, but the browser holds-off on firing the script until the html parser reaches the script tag. Still, this is not all machines, and using defer/async makes even those spanking new browsers a hair faster due to allowing extra internal optimizations in the layout engine: fewer paint events means faster sites and apps.