Olen
Olen

Reputation: 1185

Prevent CSS document from loading on mobile devices

Trying to increase the loading speed for mobile devices, and there is at least one CSS document I don't want to be loaded on mobile.

I have already prevented a script from loading, but the CSS document is kinda different.

Here is an example of what I don't want to be loaded on mobile devices:

<link rel="stylesheet" href="<?php bloginfo('stylesheet_directory'); ?>/css/animations.css">

Do you have a working solution?

Not sure what tags are the most correct, as this could probably be done by a CSS in the beginning of the document, or jQuery or HTML.

Upvotes: 2

Views: 360

Answers (5)

Mike Brant
Mike Brant

Reputation: 71384

Since you already have javascript-based mobile detection (you should have noted this in OP as it is REALLY important), you can use javascript to load the CSS. You could do something as simple as:

<script>
if(!isMobile.any()) {
    document.write('<link rel="stylesheet" href="<?php bloginfo('stylesheet_directory'); ?>/css/animations.css">');
}
</script>

This is a very simple approach. It might actually be better to use DOM manipulation to insert this link. Check out this SO answer for more thoughts on how you can do that - How to load up CSS files using Javascript?

Upvotes: 1

user4651781
user4651781

Reputation: 28

You can use the media atribute to optionally load CSS files based on viewport size...

<link rel="stylesheet" href="<?php bloginfo('stylesheet_directory'); ?>/css/animations.css" media='screen and (min-width: 800px)'>

Though this depends on what you call a "mobile device"

Upvotes: 0

Brandon Babb
Brandon Babb

Reputation: 186

Option 1: Use PHP to check the user agent string and compare it against known mobile browsers. http://php.net/manual/en/function.get-browser.php

Option 2: Use Javascript to check the user agent string and/or window width/height and add the CSS if it checks out.

Option 3: Use a media query and @import if the targeted device checks out https://css-tricks.com/snippets/css/media-queries-for-standard-devices/

Upvotes: 2

Huang Chen
Huang Chen

Reputation: 1205

You can use media queries for all your css to determine when to use css and when to not

Example: @media (max-width:600px)

Upvotes: -2

Jjsg08
Jjsg08

Reputation: 124

http://mobiledetect.net/ This can be a good option for you, only put

<?php if($detect->is("Crhome")){ ?><link rel="stylesheet" href="<?php bloginfo('stylesheet_directory'); ?>/css/animations.css"><?php } ?>

Upvotes: 0

Related Questions