1

I have a requirement to add a js file only for IE (6, 7, 8) browsers. The following script works fine and sometime it doesn't. I cleared the cache several times but has no difference.I don't know where I am going wrong . Is there anything to do with drupal_add_js for IE?

function mymodule_init() {
  if(strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE')) {
    $theme_path = drupal_get_path('theme', 'mythemename');
    $js_path = $theme_path . '/script/modernizr.js';
    drupal_add_js($js_path, 'external');
  }
}

// The code modified to true for all browsers it works for all browsers but not in IE 
function mymodule_init() {
  if(1)) {
    $theme_path = drupal_get_path('theme', 'mythemename');
    $js_path = $theme_path . '/script/modernizr.js';
    drupal_add_js($js_path, 'external'); // loading in all browsers except IE
  }
}
4
  • The "external" option is not applicable here Jun 19, 2014 at 15:47
  • Get rid of your if statement as well, it's not required. Jun 19, 2014 at 15:48
  • What I meant to say if you should get rid of the if statement and do browser detection in your javascript. Jun 19, 2014 at 16:49
  • Thanks Scott Joudry, removing the external has done the trick Jun 20, 2014 at 5:21

3 Answers 3

0

The problem is, you're using hook_init which is not run on cached pages.

Because your cache isn't varying by user agent, you're not getting a consistent response.

An easy solution would be to use something like a conditional IE tag in your theme html.tpl.php and add the JS in there:

e.g:

<!--[if !IE]>
<script type="text/javascript" src="/sites/all/themes/mytheme/script/modernizr.js"></script>
<![endif]-->
0

As you may be suspected, the original condition is wrong. Here's a related post on how someone was able to find a better condition for checking the user agent for IE:

https://stackoverflow.com/questions/5302302/php-if-internet-explorer-6-7-8-or-9

summary: use this instead:

if(preg_match('/(?i)msie [1-8]/',$_SERVER['HTTP_USER_AGENT'])){}
0

Try the Conditional styles module

Without this module, the only way to have IE conditional stylesheets was to add 37 lines of code (more if you want to add more than one stylesheet) in four horribly-difficult-to-remember function calls to your theme's template.php. Blech. Who wants that?

This module allows Drupal 7 themes to easily add conditional stylesheets to the theme's .info file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.