Improve scripts loading - Head JS loader and Drupal

Stumbled upon head.loader.js which drastically improves scripts loading. See the tests here http://headjs.com/test/script.html

From the documentation (http://headjs.com/#theory):
"Head JS frees the page from script loading burden. The scripts loading is separated from the page rendering and they are always loaded in paraller no matter how many of them and what the browser is. The difference on the user experience can be dramatic especially on the initial page load when the scripts are not yet in cache. It's your crucial first impression."

Experimental code for implementing head.loader.js in Drupal 7. Comments welcome

#rev2

<?php
function mytheme_js_alter(&$javascript) {
 
$scripts = array();
 
// sort the scripts so they are in the right order
 
uasort($javascript, 'drupal_sort_css_js');
  foreach(
$javascript as $key => $item) {
    if (
$item['type'] == 'file' || $item['type'] == 'external') {
     
$scripts[] = """ . base_path() . $item['data'] . """;
      unset(
$javascript[$key]);
    }
  }
  if (isset(
$scripts)) {
   
// add the head.loader.js script
   
$javascript['scripts/head.loader.js'] = array(
     
'scope' => 'header',
     
'type' => 'file',
     
'data' => drupal_get_path('theme', 'mytheme') . '/scripts/head.loader.js',
    );
   
// add the js function call
   
$javascript['inline.head.loader'] = array(
     
'scope' => 'header',
     
'type' => 'inline',
     
'data' => 'head.js(' . implode(',', $scripts) . ');',
     
'group' => 1,
    );
  }
}
function
mytheme_preprocess_html_tag(&$variables) {
  if (
$variables['element']['#tag'] == 'script' && isset($variables['element']['#value'])) {
   
// don't append anything to head.js call
   
$pos = strpos($variables['element']['#value'], 'head.js');
    if (
$pos === FALSE) {
     
// add head.ready to all scripts, so they are called when
      // all the files are loaded by head.js()
     
$variables['element']['#value'] = 'head.ready(function() {' . $variables['element']['#value'] . '});';
    }
  }
}
?>



Need Drupal Theming? Hire us