Dynamically load stylesheets

后端 未结 3 644
慢半拍i
慢半拍i 2021-01-02 14:03

i know that you can have style-sheets in the head of a page, but i like to have them in a separate file. Now i\'m working with a single page application.

Well in an

3条回答
  •  一向
    一向 (楼主)
    2021-01-02 14:47

    You should look into asychronously loading assets, such as the famous google-analytics code. You can load external stylesheets using Javascript.

    JavaScript

    (function(){
      var styles = document.createElement('link');
      styles.rel = 'stylesheet';
      styles.type = 'text/css';
      styles.media = 'screen';
      styles.href = 'path/to/css/file';
      document.getElementsByTagName('head')[0].appendChild(styles);
    })();
    

    Lines 1 and 7 create a new scope for variables such that local variables do not collide or override with globally scoped variables. It isn't necessary just a best practice. This solution also assumes you have a tag in your html.

提交回复
热议问题