Load JS last, or it will halt the browser while loading… AMEN!
You may protest:
But i use some inline javascript and nothing will work, when jQuery / Prototype / Mootolls / … is not loaded already!!
Version 1: content_for :js
#in your body: (HAML example, works for ERB too...) %h1 My great title - content_for :js do :javascript $(function(){ $('h1').html('inline js rocks!') }); #in you footer =js_tag 'jquery', 'application', 'whatever' yield :js #this will output all content_for blocks...
Instantly better load times, and no need to abandon inline js!!
Version 2: Caching !?
When action/fragment-caching, this can get problematic, since the content_for will not be call, and hence the js will be missing.
This can be fixed by introducing a ‘later’ method, which gets filled with everything that should be done once your js framework is loaded.
#in your views later(function(){ $('#xxx').do_something(); }) #in you footer later(); //call all those methods that have been stacked... #in your head later = function(){ var stack = [], i_ran=0; return function(execute_later){ if(typeof(execute_later)=='undefined'){ i_ran=1; for(var i=0;i<stack.length;i++)stack[i].call();//execute them all } else { if(i_ran)execute_later.call()//page is loaded already, just execute else stack.push(execute_later)//page not finished, store } }; }()
really cool tips, specially the later one. thanks
just updated it with i_ran, so that code that gets loaded after the page was finished(ajax) can run too