Dynamically load css stylesheet and wait for it to load

后端 未结 4 1632
失恋的感觉
失恋的感觉 2020-12-11 03:37

I have a script that detects a button click on which it will attach a CSS stylesheet to the "head" with jQuery like so:



        
4条回答
  •  感动是毒
    2020-12-11 03:44

    To get around race conditions when inserting a style sheet link dynamically and then relying on those calculations:

    function downloadCSS(url) {
        function insertCss(code) {
            var style = document.createElement('style');
            style.type = 'text/css';
            style.innerHTML = code;
            document.querySelector("head").appendChild(style);
        }
    
        return new Promise(async (resolve, reject) => {
            try {
                let src = await axios.get(url);
                insertCss(src.data);
            } catch (e) {
                return reject(e);
            }
    
            requestAnimationFrame(function () {
                resolve();
            });
        });
    }
    
    (async function setup() {
        try {
            await downloadCSS('https://myapp.com/style.css');        
        } catch (e) {
            return reject(e);
        }
        
        //rest of code
    })();
    

    I'm using the axios library for HTTP requests, but you can use anything you like.

    The idea is that you await the downloadCSS promise which downloads the url of your CSS, then inserts the code as a style as opposed to link element, then on the next frame resolves the promise and continues from there.

提交回复
热议问题