0

I think I have a great idea to make my site load faster in mobile: "don't load the custom fonts in small screens"

I know how to style/change the font used depending on screen size with media queries and css. What I don't know is how to prevent the custom fonts from loading in small screens. I use google fonts and I enqueue them in functions.php, but I'm open to your workarounds.

Btw, this how to do it, when using @font

2

WordPress has wp_is_mobile() function to detect mobile and handheld devices. You can use that to define your enqueue function to load fonts conditionally.

You can enqueue fonts for non mobile devices like this.

function my_enqueue_function() {

  if ( !wp_is_mobile() ) {

    wp_enqueue_style( 'gfonts', 'http://fonts.googleapis.com/css?family=Arbutus+Slab', false, NULL, 'all' );

  }

}
add_action( 'wp_enqueue_scripts', 'my_enqueue_function' );
  • Thanks. Do you have any experience of this code in action? Does it work as it should/expected? – IXN Sep 19 '15 at 10:22
  • Yes. It works great. Used it on couple of projects. The only downside you might experience is that this function wp_is_mobile() does not differentiate between mobile and tablets. It considers both the same. In your case, this might not be a huge problem but on a project where you want to only target tablets, it will not work. :) – Robert hue Sep 19 '15 at 10:26
0

I found this (partial?) solution:

Use wp_is_mobile() when you enqueue your fonts, like this:

function my_scripts() {
    // Load if not mobile
    if ( ! wp_is_mobile() ) {
         wp_enqueue_style( 'my-google-fonts', 'https://fonts.googleapis.com/css?family=Nicefont:400,500' );
    }
    // your other scripts that you enqueue...
    }
    add_action( 'wp_enqueue_scripts', 'my_scripts' );

references: codex and other question

There is also this plug-in, but I think it is overkill for my requirements.

  • Cool so you also found it. :) – Robert hue Sep 19 '15 at 10:18

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.