Load external Google Fonts stylesheet with YepNope

2019-04-14 12:44发布

问题:

I'm trying to load a dynamically generated Google Font stylesheet using Modernizr (YepNope) but always get this error:

Uncaught SyntaxError: Unexpected token ILLEGAL (css:1)

My stylesheet looks like this:

http://fonts.googleapis.com/css?family=Holtwood+One+SC

and I'm calling it via

Modernizr.load({
    load: ['css!http://fonts.googleapis.com/cssfamily=Holtwood+One+SC|Terminal+Dosis:700'],
    callback: 
        function (url, result, key) {
            console.log('loaded...!');          
        }       
});

The website says this but for some reason it just won't work. I think the resource is parsed as a script file and that's what cause the error, but can't seem to make it work =(

"With the css! prefix, you can prepend it to any file name and yepnope will treat it like a css file."

Anyone had success achieving something similar? Thanks!

回答1:

Make sure you are adding the css prefix file to your copy of yepnope. It works like a jQuery plugin.

You can get it at:

https://github.com/SlexAxton/yepnope.js/blob/master/prefixes/yepnope.css-prefix.js



回答2:

Or, you can call Google Webfont API, such as:

Modernizr.load({
 load: 'http://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js',
 complete: function () {

  WebFont.load({
   google: {
    families: ['Open+Sans:300,400,700']
   }
  });
 }
});

Ideally should also have use a no-js fallback to load the fonts from your server using a timed function or another, like:

if (!window.jQuery) {
 Modernizr.load('http://d.clickmetrics.cl/assets/js/scaffolding/jquery-1.9.0.min.js');
}