1

I want to add something like this to my page header, in order to load a js and css file only if NOT an iPhone/iPad:

if(!(navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)))
{
    //Link to js file
    //Link to css file
}

The first line works fine, I've tested it by pasting in a script, but I'm not sure how to get the files linked... especially as I'd like the js and css links to start with the WP template tag <?php echo get_stylesheet_directory_uri(); ?>

Thank you in advance for your help!

Caroline Elisa
  • 1,246
  • 6
  • 18
  • 35
  • You could check the navigator server-side (so directly within PHP) and use the WP api to add JS and CSS files. Otherwise you need to pass the directory URI as a JS variable into the page and re-use it there conditionally. – hakre Feb 23 '12 at 14:30
  • Not the answer, but that if statement is actually checking that its `not an iPhone` or `is an iPod`. `if(!(navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPod/i)))` might be what you want – Josh Feb 23 '12 at 14:32
  • possible duplicate of [Passing Variables from PHP to JS](http://stackoverflow.com/questions/8775680/passing-variables-from-php-to-js) – hakre Feb 23 '12 at 14:32
  • try out [this link](http://www.javascriptkit.com/javatutors/loadjavascriptcss.shtml), that'll do i guess – giorgio Feb 23 '12 at 14:33

3 Answers3

5
<?php
    if (!preg_match("{iPhone|iPod}i",$_SERVER['HTTP_USER_AGENT']))
    {
       echo '<script src="yourscript.js"></script>';
       echo '<link href="yourstyle.css" rel="stylesheet" type="text/css">';
    }
?>
Tomas M
  • 51
  • 1
1

Something like that:

<?php if(!(navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) : ?>
    <link href="<?php echo get_stylesheet_directory_uri() ?>/main.css" type="text/css" rel="stylesheet" >
    <script src="<?php echo get_stylesheet_directory_uri() ?>/main.js" type="text/javascript"></script>
<?php endif ?>
seferov
  • 4,111
  • 3
  • 37
  • 75
1

It's better to check the user agent using PHP, since it's easier to then add the right HTML tags to load the right css and js files.

<?php if ( !preg_match( '/iPhone/', $_SERVER['HTTP_USER_AGENT'] ) && !preg_match( '/iPod/', $_SERVER['HTTP_USER_AGENT'] ) ): ?>
  <link href="<?php echo get_stylesheet_directory_uri() ?>/style.css">
  <script src="<?php echo get_stylesheet_directory_uri() ?>/script.js" type="text/javascript"></script>
<?php endif; ?>

Doing it using just javascript would add unneeded complexity, and need you to use a js loader as RequireJS http://requirejs.org/

Davide
  • 2,329
  • 1
  • 14
  • 12