DEV Community

Discussion on: Lazy-loading style sheets with your own JavaScript function

Collapse
lukeshiru profile image
LUKESHIRU

There are some better strategies to defer non-critical CSS, but if you really want to write your own code, you can simplify it quite a bit:

/**
 * @param {string|ReadonlyArray<string>} paths
 */
const lazyLoadCSS = paths =>
    (Array.isArray(paths) ? paths : [paths]).forEach(href =>
        href
            ? document.querySelector("head").appendChild(
                Object.assign(document.createElement("link"), {
                    href,
                    rel: "stylesheet"
                })
            )
            : undefined
    );
Enter fullscreen mode Exit fullscreen mode

Cheers!