markdownclient-sidehtml-renderingjavascript-marked

Client-side rendering of a Markdown file


One can follow the Marked library documentation and render a Markdown string inline. This is a working code snippet.

<div id="content"></div>
  <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
  <script>
    document.getElementById('content').innerHTML =
      marked.parse('# Hello Ayan \n\nRendered by **marked**.');
  </script>

Is there a way to pass a file into the marked.parse function or through any other client-side Markdown rendering library and render the whole file instead of just a string? I looked into getting the markdown file and passing it as a string. However, I couldn't find a straightforward way.

The file is in the same folder as this HTML file and would be served from GitHub using GitHub Pages. However, I could use an absolute link from a CDN if needed. How would I pass the contents to marked.parse()? marked.parse(Hello.md) didn't work.


Solution

  • The file is in the same folder as this HTML file and would be served from GitHub using GitHub Pages

    You can have the browser fetch the content and then pass its content to marked.parse(). Something like this should work:

    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
    <script>
      fetch("/pages-site/markdown.md")      // The path to the raw Markdown file
        .then(response => response.blob())  // Unwrap to a blob...
        .then(blob => blob.text())          // ...then to raw text...
        .then(markdown => {                 // ...then pass the raw text into marked.parse
          document.getElementById("content").innerHTML = marked.parse(markdown);
        });
    </script>
    

    Here is a live example.