Skip to content

Instantly share code, notes, and snippets.

@googlicius
Created May 3, 2018 03:38
Show Gist options
  • Select an option

  • Save googlicius/e07b6ce82a8020ccc809a17955b85213 to your computer and use it in GitHub Desktop.

Select an option

Save googlicius/e07b6ce82a8020ccc809a17955b85213 to your computer and use it in GitHub Desktop.

Revisions

  1. googlicius created this gist May 3, 2018.
    43 changes: 43 additions & 0 deletions loadAsyncCss.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,43 @@
    // Load CSS file async
    export const loadAsyncCss = (href: string | Array<string>, id, cb: () => void = null) => {
    function createElement(d, s, href) {
    var link = d.createElement(s);
    link.href = href;
    link.rel = 'stylesheet';
    return link;
    }
    (function (d, id, href, r) {
    var fjs = d.getElementsByTagName('link')[0];
    var promises: Array<Promise<any>> = [];
    const ID_CSS = id + '-css';

    if (d.getElementById(id) || d.getElementById(ID_CSS)) {
    if (typeof r == 'function') {
    r();
    }
    return;
    }

    if (typeof href == 'string') {
    href = [href];
    }

    href.forEach((href_str, i) => {
    var link = createElement(d, 'link', href_str);
    if (i == href.length - 1) {
    link.id = ID_CSS;
    }
    fjs.parentNode.insertBefore(link, fjs);
    var promise = new Promise((resolve, reject) => {
    link.onload = function () {
    resolve();
    }
    });
    promises.push(promise);
    });

    if (typeof r == 'function') {
    Promise.all(promises).then(() => r());
    }
    }(document, id, href, cb));
    }