Unload/remove dynamically loaded css files

主宰稳场 提交于 2020-08-09 12:25:34

问题


After loading a css file like this:

const themes = ['dark-theme.css', 'light-theme.css'];
async function loadcss(file) {
    return await import(file);
}
loadcss(themes[0]).then(console.log)

The console output is an empty object for me and a new annonymous < style> tag sits in the < head> of my index.html. So far so good, but what if I (in this example) want to change the theme to light-theme.css. That would merge both themes as dark-theme.css is already loaded.

Is there a way to remove the < style> tag from the DOM?

To furthermore specify my question, the provided example shows an abstracted behaviour and I am only interested in removing the dynamically loaded css from the DOM.


回答1:


I don't know vue.js but here is simple example in React hope it helps somehow :) perhaps some ideas at least :)

class TodoApp extends React.Component {
  static themes = {
    dark: 'dark-theme.css', 
    light: 'light-theme.css',
  };

  render() {
    return ReactDOM.createPortal(
        (<link rel="stylesheet" href={TodoApp.themes.dark} type="text/css"></link>),
      document.head
    );  
  }
}

ReactDOM.render(<TodoApp />, document.querySelector("#app"))

http://jsfiddle.net/3y4hw2ox/




回答2:


Thanks to OZZIE, I questioned my methodology and found, that importing the css files, like my question shows (through ES6 import, or require.context(...)), is not usefull, as we can't identify it, we dont get access to the <style> element, leaving us with no entry to the DOM and no way to manipulate it.

Instead we will link the css files manually in the <head>, as we know their name and path.

const themes = ['dark-theme.css', 'light-theme.css'];
const head = document.body.parentElement.firstElementChild;
const link = document.createElement('link');
link.setAttribute('href', process.env.BASE_URL + themes[0]);
link.setAttribute('id', themes[0]); // set id so we can remove it later
head.appendChild(link);


来源:https://stackoverflow.com/questions/54078728/unload-remove-dynamically-loaded-css-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!