-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfont-loader.min.js
More file actions
7 lines (7 loc) · 1.98 KB
/
Copy pathfont-loader.min.js
File metadata and controls
7 lines (7 loc) · 1.98 KB
1
2
3
4
5
6
7
/**
* Lazy load fonts using the FontFace API and IntersectionObserver.
* @author Andreas Nymark <andreas@nymark.co>
* @license MIT
* @version 1.2.1
* @link https://github.com/andreasnymark/font-loader
*/export const config=Object.assign({eagerSelector:'[data-font-load="eager"]',lazySelector:'[data-font-load="lazy"]',metadataSelector:"#font-metadata",fontsLoadedClass:"fonts-loaded",fontLoadedClass:"font-loaded",rootMargin:"300px",threshold:0,applyFont:!1},window.FontLoaderConfig||{});const r=document.querySelector(config.metadataSelector);r||console.warn("font-metadata element not found, font loading disabled");let n={};if(r)try{n=JSON.parse(r.textContent)}catch(t){console.error("Failed to parse font metadata:",t)}const s=new Map;export function loadFont(t){if(s.has(t))return s.get(t);const e=n[t];if(!e)return console.warn("Font not found:",t),Promise.resolve();const o=new FontFace(e.family,`url(${e.url})`,{weight:e.weightValue||"normal",style:e.style||"normal",stretch:e.stretch||"normal"}).load().then(a=>{document.fonts.add(a)}).catch(a=>{console.error("Failed to load font:",e.name,a)});return s.set(t,o),o}const d=new IntersectionObserver(t=>{t.forEach(e=>{if(e.isIntersecting){const o=e.target,a=o.dataset.fontFamily;if(a){const l=n[a];o.style.fontStyle=l?.style||"normal",o.style.fontWeight=l?.weightValue||"normal",loadFont(a).then(()=>{o.classList.add(config.fontLoadedClass),config.applyFont&&(o.style.fontFamily=`'${l?.family}'`)})}d.unobserve(o)}})},{rootMargin:config.rootMargin,threshold:config.threshold});function c(){document.querySelectorAll(config.eagerSelector).forEach(t=>{const e=t.dataset.fontFamily;if(e){const o=n[e];t.style.fontStyle=o?.style||"normal",t.style.fontWeight=o?.weightValue||"normal",loadFont(e).then(()=>{t.classList.add(config.fontsLoadedClass),config.applyFont&&(t.style.fontFamily=`'${o?.family}'`)})}}),document.querySelectorAll(config.lazySelector).forEach(t=>{d.observe(t)})}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",c):c();