Inject CSS stylesheet as string using Javascript

后端 未结 4 1267
一整个雨季
一整个雨季 2020-11-30 01:37

I\'m developing a Chrome extension, and I\'d like users to be able to add their own CSS styles to change the appearance of the extension\'s pages (not web pages). I\'ve look

4条回答
  •  被撕碎了的回忆
    2020-11-30 02:17

    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.

    Or, if you want to import all styles at the same time, you can do something like this:

    function loadStyles(srcs) {
        let promises = [];
        srcs.forEach(src => promises.push(loadStyle(src)));
        return Promise.all(promises);
    }
    

    Use it like this:

    loadStyles([
        'css/style.css',
        'css/icomoon.css'
    ]);
    

    You can implement your own methods, such as importing scripts on priorities, importing scripts simultaneously or importing styles and scripts simultaneously. If i get more votes, i'll publish my implementation.

    If you want to learn more about Promises, read more here

提交回复
热议问题