Caroline Elisa
Caroline Elisa

Reputation: 1246

Adding a links to js and css files within a conditional script in page header

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!

Upvotes: 1

Views: 492

Answers (3)

Davide
Davide

Reputation: 2339

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/

Upvotes: 1

Tomas M
Tomas M

Reputation: 51

<?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">';
    }
?>

Upvotes: 5

seferov
seferov

Reputation: 4161

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

Upvotes: 1

Related Questions