Last active
December 23, 2015 22:39
-
-
Save pascalduez/6704554 to your computer and use it in GitHub Desktop.
Drupal 7 — Add JS with conditional comments
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.