Skip to content

Instantly share code, notes, and snippets.

@ntwcklng
Last active September 3, 2015 09:43
Show Gist options
  • Save ntwcklng/c381f866321ab6b00600 to your computer and use it in GitHub Desktop.
Save ntwcklng/c381f866321ab6b00600 to your computer and use it in GitHub Desktop.
Try different Google Fonts on your (live) Website in seconds!
// Change the NEWFONT var to the Font you want to try out and paste this script into the console.
// Of Course your website needs to be fully loaded
// Type the font name without any special chars
// Example: "Varela Rond", "Open Sans", "Roboto", "Slabo 27px", ...
var NEWFONT = "Varela Round"; // Select any font from https://www.google.com/fonts
(function(d) {
var link = d.createElement("link");
var img = d.createElement("img");
link.href = "https://fonts.googleapis.com/css?family=" + NEWFONT.replace(" ", "+");
link.rel = "stylesheet";
link.type = "text/css";
d.querySelectorAll("head")[0].appendChild(link);
// onerror only gets fired, when the img is executed and the browser knows
// that a stylesheet is not a valid image ;)
img.onerror = function() {
for(var i=0, els=d.querySelectorAll("*"); i < els.length; i++){
els[i].style.fontFamily = NEWFONT;
};
}
d.body.appendChild(img);
img.src = link.href;
})(document);
var NEWFONT="YOURFONTHERE";!function(a){var b=a.createElement("link"),c=a.createElement("img");b.href="https://fonts.googleapis.com/css?family="+NEWFONT.replace(" ","+"),b.rel="stylesheet",b.type="text/css",a.querySelectorAll("head")[0].appendChild(b),c.onerror=function(){for(var b=0,c=a.querySelectorAll("*");b<c.length;b++)c[b].style.fontFamily=NEWFONT},a.body.appendChild(c),c.src=b.href}(document);
// easy copying
@ntwcklng
Copy link
Author

ntwcklng commented Sep 3, 2015

This script appends a link tag with your chosen font from Google Fonts. When the stylesheet is fully loaded, it loops through all elements and changes the fontFamily.

The onerror event is key. The browser first downloads the complete stylesheet and then notice that it it's not an image. So the onerror fires and we are sure the font is fully loaded.

@ntwcklng
Copy link
Author

ntwcklng commented Sep 3, 2015

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment