Skip to content

Instantly share code, notes, and snippets.

@danielpaul
Created July 30, 2025 15:02
Show Gist options
  • Save danielpaul/efa462f9e885f2f8d0060bbfb065e2c0 to your computer and use it in GitHub Desktop.
Save danielpaul/efa462f9e885f2f8d0060bbfb065e2c0 to your computer and use it in GitHub Desktop.
Load Google Fonts Based on Cookie Consent
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