Last active
September 3, 2015 09:43
-
-
Save ntwcklng/c381f866321ab6b00600 to your computer and use it in GitHub Desktop.
Try different Google Fonts on your (live) Website in seconds!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.