Is there any way to load css and javascript from a string?

后端 未结 3 993
我寻月下人不归
我寻月下人不归 2021-01-06 10:30

I\'ve seen many examples of loading CSS and javascript dynamically from a file. Here\'s a good example. But is there a way to load CSS or javascript as a string? For exam

3条回答
  •  时光取名叫无心
    2021-01-06 11:25

    Another way without using potentially dangerous eval and innerHTML is creating a link element with base64 encoded URL:

    function loadCSS(cssStyles) {
      const link = document.createElement('link');
      link.href = `data:text/css;base64,${btoa(cssStyles)}`;
      link.type = 'text/css';
      link.rel = 'stylesheet';
      document.getElementsByTagName('head')[0].appendChild(link);
    }
    

提交回复
热议问题