Blog

Kicking Javascript to the Footer in Drupal 8?

As a platform, Drupal has excellent javascript support. Drupal 7 will ship with jQuery 1.4.2 and jQuery UI 1.8, which will make it even easier to build rich user interactions with Drupal.

Drupal supports aggregating javascript files to reduce the number of network connections a browser must open to load a page. It is common practice for Drupal themes to put the <script> tag in the <head> section of the page. Unfortunately this has a performance impact, as all browsers will stop processing the page and start loading and processing the referenced javascript file. For this reason, both Yahoo! and Microsoft recommend placing all javascript just before the closing </body> tag in a page so it is loaded and processed after the content.

Making this change in Drupal is a pretty straight forward process. It is already possible to do this in Drupal 6 or 7. My site places the $scripts variable at the end of the page. Unfortunately some modules rely on javascript being in the <head>er, and some even place <script>s in the body to allow inline function calls.

It is too late to implement this change in Drupal 7, but the transition can occur now. Documentation can be updated to inform theme developers that they can place the $script variable at the end of the page, just above where the $closure variable is placed. The module development guide can be updated to strongly recommend against relying on the value ‘header’ for the ‘scope’ element of the $options array for drupal_add_js() meaning that the javascript will end up in the header and to not place any inline javascript code in themes or modules. In Drupal 8 the scope element for the $options array can be dropped.

If theme and module developers adopt this best practice approach for their Drupal 7 releases there should be minimal transition work for this change in the version 8 release cycle.

I am hoping to discuss this at the Core Developers Summit at DrupalCon Copenhagen later this month.