Created
July 30, 2025 15:02
-
-
Save danielpaul/efa462f9e885f2f8d0060bbfb065e2c0 to your computer and use it in GitHub Desktop.
Load Google Fonts Based on Cookie Consent
This file contains hidden or 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
function loadGoogleFonts(fontFamily = 'Open Sans') { | |
const link = document.createElement('link'); | |
link.href = `https://fonts.googleapis.com/css2?family=${fontFamily.replace(/ /g, '+')}&display=swap`; | |
link.rel = 'stylesheet'; | |
document.head.appendChild(link); | |
} | |
function removeGoogleFonts() { | |
const existingLink = document.querySelector('link[href^="https://fonts.googleapis.com/"]'); | |
if (existingLink) { | |
existingLink.remove(); | |
} | |
} | |
// cookiechimp.com CMP | |
window.addEventListener("cc:onUpdate", function (event) { | |
// Check if the 'preferences' category (or your custom category for fonts) is accepted | |
if (CookieChimp.acceptedService("Google Fonts", "preferences")) { | |
loadGoogleFonts(); | |
} else { | |
removeGoogleFonts(); | |
} | |
}); | |
// Initial check on page load in case consent is already given | |
if (typeof CookieChimp !== 'undefined' && CookieChimp.acceptedService("Google Fonts", "preferences")) { | |
loadGoogleFonts(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment