How to load up CSS files using Javascript?

后端 未结 19 3335
栀梦
栀梦 2020-11-21 07:51

Is it possible to import css stylesheets into a html page using Javascript? If so, how can it be done?

P.S the javascript will be hosted on my site, but I want users

19条回答
  •  春和景丽
    2020-11-21 07:59

    Have you ever heard of Promises? They work on all modern browsers and are relatively simple to use. Have a look at this simple method to inject css to the html head:

    function loadStyle(src) {
        return new Promise(function (resolve, reject) {
            let link = document.createElement('link');
            link.href = src;
            link.rel = 'stylesheet';
    
            link.onload = () => resolve(link);
            link.onerror = () => reject(new Error(`Style load error for ${src}`));
    
            document.head.append(link);
        });
    }
    

    You can implement it as follows:

    window.onload = function () {
        loadStyle("https://fonts.googleapis.com/css2?family=Raleway&display=swap")
            .then(() => loadStyle("css/style.css"))
            .then(() => loadStyle("css/icomoon.css"))
            .then(() => {
                alert('All styles are loaded!');
            }).catch(err => alert(err));
    }
    

    It's really cool, right? This is a way to decide the priority of the styles using Promises.

    To see a multi-style loading implementation see: https://stackoverflow.com/a/63936671/13720928

提交回复
热议问题