htmlcssimport

Dynamically load stylesheets


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

In an SPA the content is dynamic, right? So I didn't want to import all the style-sheets in the head section with link tags. Can I somehow import style-sheets as-and-when I need them?

I mean, can I have a link in the body, such that whenever my SPA loads some dynamic content, a style sheet also gets loaded? Such that I don't have to load all the stylesheets even when the dynamic content is not loaded..

I stress again: Whenever the content loads, the styles load.

I know I can do it with the help of an inline style like this:

~PSEUDO CODE 
<tagname style="somestyle"></tagname>

But can I have some dynamic file imports too? Can I have the link tag in the body too? Even if it works, is it standard?


Solution

  • 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 <head> tag in your html.