Using Head.js in WordPress and Rails 3
Javascript & jQuery Development
So, we’ve had a few requests to publish the code we created to using Head.js in WordPress.
We’ve been swamped, but here it is. And, since we took so long publishing it, we’re also adding the code for sticking it into Rails 3 projects.
In your functions.php file
[php]
remove_action("wp_head","wp_print_head_scripts",9);
remove_action(‘wp_footer’, ‘wp_print_footer_scripts’);
add_action("wp_head","hbgs_wp_print_head_scripts",9);
function hbgs_wp_print_head_scripts() {
if ( ! did_action(‘wp_print_scripts’) )
do_action(‘wp_print_scripts’);
global $wp_scripts;
if ( !is_a($wp_scripts, ‘WP_Scripts’) )
return array(); // no need to run if nothing is queued
ob_start();
print_head_scripts();
print_footer_scripts();
$output = ob_get_contents();
ob_end_clean();
$matches = array();
preg_match_all(‘|<script.+src=["'](.+)["'].+</script>|’,$output,$matches);
$scripts = implode("’,'",$matches[1]);
if($scripts) {
$new_output = "<script>head.js(‘$scripts’);</script>";
} else {
$new_output = "";
}
echo $new_output;
return $wp_scripts->done;
}
[/php]
We’re essentially removing footer scripts since Head.js takes care of deferring the loading anyway. Then we run a regex on the scripts, extract the source and add them all to the call to head.js.
Then, stick all your inline javascript into a head.ready call like this
[js]
head.ready(function() {
(function($){
<?php echo get_option("footer_javascript") ?>
}(jQuery));
});
[/js]
As for Rails, here is what we do:
[js]
head.js(<%= raw (javascript_include_tag(:defaults)+content_for(:external_javascripts)).scan(/src=(['"][^'"]+['"])/).join(",") %>);
head.ready(function() {
(function($){
<%= strip_tags(content_for(:javascripts)) %>
}(jQuery));
});
[/js]
Then, in our views, we can add:
[ruby]
<% content_for(:javascripts) do %>
<script>
…
</script>
<% end %>
[/ruby]
and
[ruby]
<% content_for :external_javascripts do -%>
<%= javascript_include_tag "libs/jquery.validationEngine-#{I18n.locale}.js" %>
<%= javascript_include_tag "libs/jquery.validationEngine.js" %>
<% end -%>
[/ruby]
That’s it!