Search code examples
githubgist

How to reference a gist stylesheet in another gist?


I created a gist that has a html page and a css file. How would I reference the css file in the html page?

I tried a few ways but none of them seems working. The html page is at: https://gist.github.com/yuipcheng/943286be35fd690f499d59534281a6c5

Viewing page: https://gistpreview.github.io/?943286be35fd690f499d59534281a6c5


Solution

  • gistpreview.github.io loads the html with Javascript by using the Github Gist API. From the source code it just writes the html content. So, it doesn't deal with relative links that may link to other css files.

    You would need to :

    • fork the gistpreview project
    • after the html rendering (document.write), iterate over the link tags and check if they are present in the files field of the API result
    • load the css content dynamically if matching

    I've tested this method above using this fork.

    Example for you gist: https://bertrandmartel.github.io/gistpreview.github.io/?943286be35fd690f499d59534281a6c5

    Code before :

    var content = info.files[fileName].content;
    document.write(content);
    

    Code after :

    var content = info.files[fileName].content;
    document.write(content);
    
    //load links
    var links = document.querySelectorAll("link");
    for (let [key, value] of Object.entries(info.files)) {
      for (var i = 0; i < links.length; i++) {
        var href = links[i].getAttribute("href").replace(/^\/|\/$/g, '');
        if (value.filename === href && value.type === "text/css") {
          console.log("load file " + value.filename);
          var style = document.createElement('style');
          style.type = 'text/css';
          style.innerHTML = value.content;
          document.getElementsByTagName('head')[0].appendChild(style);
        }
      }
    }