简体   繁体   中英

How google fonts loads fonts dynamically

In Google fonts website ( https://fonts.google.com/ ) they add <li> elements dynamically on scroll. Those <li> elements has <a> tag with href attribute (screenshot bellow) with url value that points to the font page. Then deeper inside <li> there is <gf-content-editable> element which sets font-family CSS value to the actual font family.

Could someone explain how do they do that? Looking for a way to load fonts dynamically, but CSS Font Loading API is still experimental.

Thanks for any insights.

在此处输入图像描述

One way to do this would be to create an object using data from a database or any other source, and iterating over it to dynamically create cards. A bare-bones example of this could be:

const data = [
    {
        fontFamily: 'Open Sans',
        href: 'Open+Sans+Condensed',
        // Other attributes
    },
    // Other fonts
]

for(const font of data) {

    let li, gridItemTemplate, gfFontPreview, a, section, gfContentEditable /*other elements*/;
    li = document.createElement('li')
    li.setAttribute('class', 'grid-list-tile is-in-last-column');
    // Other attributes

    gridItemTemplate = document.createElement('grid-item-template');

    gfFontPreview = document.createElement('gf-font-preview')
    gfFontPreview.setAttribute('class', 'grid-list-font-preview');
    // Other attributes

    a = document.createElement('a')
    a.setAttribute('class', 'https://fonts.google.com/specimen' + font.href);
    // Other attributes

    section = document.createElement('section');
    section.setAttribute('class', 'font-preview-card-static ...');

    gfContentEditable = document.createElement('gf-content-editable')
    gfContentEditable.setAttribute('class', 'preview-text-font-card static-font...')
    gfContentEditable.setAttribute('style', `font-size: 40px; line-height: 1.10909; font-family: "${font.fontFamily} script=latin rev=1"; weight: 300; font-style: normal;`);
    gfContentEditable.innerText = 'Almost before we knew it, we had left the ground.';

    document
        .body
        .appendChild(li)
        .appendChild(gridItemTemplate)
        .appendChild(gfFontPreview)
        .appendChild(a)
        .appendChild(section)
        .appendChild(gfContentEditable);

}

This is a pretty verbose way of writing this out. If you actually wish to create this as a function for your website, you can abstract a lot of this code out into separate functions, or use a templating engine or library to achieve this. I'm just sharing this to show how I could achieve this with just the information I have from the question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM