Search code examples
cssresponsive-designwebfontsgoogle-webfonts

Is it possible to conditionally link a CSS font?


I'm using Google fonts in a responsive site like:

<link href='http://fonts.googleapis.com/css?family=Bangers' rel='stylesheet' type='text/css'>

However I only want to use this font when the screen is wider than 1024.

Is it possible to only link it if the screen is wider than 1024 and how?

Update: I can usee @media queries to keep the font from being displayed. What I want is for mobile devices to not have to download the font file.


Solution

  • Yes:

    <link href='http://fonts.googleapis.com/css?Bangers' 
          rel='stylesheet' 
          media='screen and (min-width: 1024px)'
          type='text/css'>
    

    You can use media queries inside you CSS as well. That way you don't need to have multiple stylesheets for different screen sizes. The download size will be bigger (the whole file is downloaded), but is saves on the number of requests, so often it's still more efficient.

    I tested this using this fiddle. In my (Chrome, desktop) browser, it does still download the CSS file, but it doesn't download the fonts it refers to. The actual fonts are in separate files. Only when I decrease min-width from 5000px to 500px it actually downloads the fonts as well.

    Technically it wouldn't need to download the CSS file, but maybe it wants to have it just in case, after all the CSS file could contain other styles that are important to have when the screen size suddenly changes (rotation of device, maximation of browser window, etc). For a font it's usually not a problem if it takes a second to download, but visibility of elements, colors, sizes should be present immediately, so that might be a good reason to download the CSS files.

    Still, whether or not the fonts are downloaded immediately depends on the optimization features of the browser. Chrome seems to be at least half-smart. Other browsers may make similar decisions. Personally I wouldn't bother to do a lot a scripting to prevent the font CSS files to be downloaded. They won't cause that much overhead (unless you have many fonts, defined in different CSS files, but that indicates poor design too).