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!

4
  • 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. Commented Feb 23, 2012 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 Commented Feb 23, 2012 at 14:32
  • possible duplicate of Passing Variables from PHP to JS Commented Feb 23, 2012 at 14:32
  • try out this link, that'll do i guess Commented Feb 23, 2012 at 14:33

3 Answers 3

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">';
    }
?>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Tomas. That adds the code, but what about the <?php echo get_stylesheet_directory_uri(); ?> part? e.g. the js link needs to be <?php echo get_stylesheet_directory_uri(); ?>/yourscript.js
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/

Comments

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 ?>

1 Comment

Thanks seferov, but that breaks the page!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.