Skip to content

Instantly share code, notes, and snippets.

@pascalduez
Last active December 23, 2015 22:39
Show Gist options
  • Save pascalduez/6704554 to your computer and use it in GitHub Desktop.
Save pascalduez/6704554 to your computer and use it in GitHub Desktop.
Drupal 7 — Add JS with conditional comments
<?php
/**
* Helper function to add IE commented js files.
* Offer more placement flexibility than drupal_add_html_head.
*/
function _add_ie_js(array $scripts) {
$return = '';
foreach ($scripts as $key => $value) {
$script = array(
'#theme' => 'html_tag',
'#tag' => 'script',
'#attributes' => array(
'type' => 'text/javascript',
'src' => file_create_url($value['file']),
),
'#browsers' => $value['condition'],
'#pre_render' => array('drupal_pre_render_conditional_comments'),
);
$return .= drupal_render($script);
}
return $return;
}
/**
* Implements hook_preprocess_html().
*/
function HOOK_preprocess_html(&$vars, $hook) {
$ie_scripts = array();
// Selectivizr. (For instance...)
if ($selectivizr = libraries_get_path('selectivizr')) {
$ie_scripts['selectivizr']['file'] = $selectivizr . '/selectivizr.js';
$ie_scripts['selectivizr']['condition'] = array('IE' => 'lt IE 9', '!IE' => FALSE);
}
$vars['ie_scripts'] = _add_ie_js($ie_scripts);
}
@surreymagpie
Copy link

I found this useful but it produces a self-closing tag, i.e. <script />, which doesn't work properly.

I would suggest you add '#value' => '', to your array so that you produce a separate </script> tag.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment