Last active
June 18, 2021 20:30
-
-
Save npanuhin/7d871ae4584b500dcc0c8d209ef24cf6 to your computer and use it in GitHub Desktop.
Lazy loading fonts and styles (JS)
This file contains 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 loadFont(name, local=[], | |
eot=undefined, woff=undefined, woff2=undefined, ttf=undefined, | |
font_weight="normal", font_style="normal", font_display="auto") { | |
name = `font-family:'${name}';`; | |
let eot_sep = (eot == undefined ? '' : `src:url('${eot}');`); | |
paths = []; | |
for (let path of local) paths.push(`local('${path}')`); | |
if (eot !== undefined) paths.push(`url('${eot}?#iefix')format('embedded-opentype')`); | |
if (woff2 !== undefined) paths.push(`url('${woff2}')format('woff2')`); | |
if (woff !== undefined) paths.push(`url('${woff}')format('woff')`); | |
if (ttf !== undefined) paths.push(`url('${ttf}')format('truetype')`); | |
paths = paths.join(","); | |
paths = `src:${paths};` | |
font_weight = `font-weight:${font_weight};`; | |
font_style = `font-style:${font_style};`; | |
font_display = `font-display:${font_display}`; // Last ';' redundant | |
let style_obj = document.createElement("style"); | |
style_obj.innerHTML = `@font-face{${name}${eot_sep}${paths}${font_weight}${font_style}${font_display}}`; | |
document.head.appendChild(style_obj); | |
} | |
function loadStyle(url, media=undefined) { | |
let style_obj = document.createElement("link"); | |
style_obj.rel = "stylesheet"; | |
style_obj.type = "text/css"; | |
if (media !== undefined) style_obj.media = media; | |
style_obj.href = url; | |
document.head.appendChild(style_obj); | |
} | |
function loadScript(url, async=false) { | |
let script_obj = document.createElement("script"); | |
script_obj.type = "text/javascript"; | |
script_obj.src = url; | |
script_obj.async = async; | |
document.body.appendChild(script_obj); | |
} | |
function loadHTMLScripts() { | |
for (let elem of document.body.getElementsByTagName("*")) { | |
if (elem.tagName.toLowerCase() == "script" && elem.dataset.src !== undefined) { | |
loadScript(elem.dataset.src); | |
elem.remove(); | |
} | |
} | |
} | |
// Usage: | |
loadFont("Segoe UI", | |
local=["Segoe UI Bold", "SegoeUIBold", "SegoeUI-Bold", "Source-UI-Bold"], | |
eot="/files/fonts/SegoeUI/SegoeUI-Bold.eot", | |
woff="/files/fonts/SegoeUI/SegoeUI-Bold.woff", | |
woff2="/files/fonts/SegoeUI/SegoeUI-Bold.woff2", | |
ttf="/files/fonts/SegoeUI/SegoeUI-Bold.ttf", | |
font_weight="bold", font_style="normal", font_display="swap" | |
); | |
loadStyle("build/mobile.css"); | |
loadHTMLScripts(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment