File: /var/www/quadcode/one-time-popup/src/utils/load-fonts /loadFonts.ts
interface LoadFontParams {
name: string;
fontUrl: string;
weight?: string;
style?: string;
display?: FontDisplay;
}
/**
* Programmatically loads a font and registers it in the document.
* The font file must be located in the public folder.
* @example
* await loadFont({
* name: 'Suisse Intl',
* fontUrl: '/fonts/SuisseIntl-Medium.woff',
* weight: '500'
* });
* @param {LoadFontParams} params - The font configuration object.
* @returns {Promise<void>} A promise that resolves after successful font registration.
*/
export const loadFont = async (params: LoadFontParams): Promise<void> => {
const font = new FontFace(params.name, `url(${params.fontUrl})`, {
weight: params.weight || '400',
style: params.style || 'normal',
display: params.display || 'swap',
});
try {
const loadedFont = await font.load();
document.fonts.add(loadedFont);
} catch (err) {
console.error('Font loading failed:', err);
}
};
/**
* Batch loads and registers multiple fonts in the Light DOM.
* Essential for resolving font rendering issues within a Shadow Root.
* @example
* const fonts: LoadFontParams[] = [
* { name: 'Suisse Intl', fontUrl: '/fonts/Suisse-Bold.woff', weight: '700' },
* { name: 'Suisse Intl', fontUrl: '/fonts/Suisse-Medium.woff', weight: '500' }
* ];
* await loadFonts(fonts);
* @param {LoadFontParams[]} fonts - An array of font configuration objects.
* @returns {Promise<void[]>} A promise that resolves once all fonts have been processed.
*/
export const loadFonts = async (fonts: LoadFontParams[]): Promise<void[]> => {
return Promise.all(fonts.map((font) => loadFont(font)));
};