How to Load Javascript Last with Inline JS

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
   }
 };
}()

2 thoughts on “How to Load Javascript Last with Inline JS

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s