markdownurl-parametershtml-renderingjavascript-markedclient-side-rendering

Embed a URL for client-side rendering of a Markdown file


One can render a Markdown file on a static site client-side using the code below.

<div id="txt"></div>
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<script>
  fetch("https://raw.githubusercontent.com/ccharles/pages-test/master/markdown.md")
      .then(r=>r.blob()).then(b=>b.text()).then(m=>{document.getElementById("txt").innerHTML=marked.parse(m)})
</script>

I found there are two ways to embed a URL in another URL. However, I couldn't figure out how to pass the Markdown file URL as a parameter to the Marked.js URL. Can one add a Markdown file URL to the GET parameter of a library URL to render Markdown to HTML client side using this or any other library? Something like this..

https://cdn.jsdelivr.net/npm/marked/marked.min.js?MDUri=https://raw.githubusercontent.com/ccharles/pages-test/master/markdown.md

@chris


Solution

  • One needs a domain to serve the code that would parse the Markdown file client side. One example of that is Docsify. PFB example

    Published by Docsify-This

    However, Docsify doesn't render the script tag in one's Markdown file. So one can serve code similar to snippet below and serve it from their own GitHub repository after enabling GitHub Pages.

    document.addEventListener("DOMContentLoaded", function() {
        fetch("https://raw.githubusercontent.com/Ayanmullick/test/master/testfolder/StachExgMdScript.md")
            .then((response) => response.text()) // Unwrap to a blob...
            .then((markdown) => {
                document.getElementById("content").innerHTML = marked.parse(markdown);
                var scriptTags = document.querySelectorAll("#content script");
                function handleDocumentWrite(content) {
                    var contentPlaceholder = document.getElementById("content");
                    contentPlaceholder.innerHTML += content}
                window.document.write = handleDocumentWrite;
                scriptTags.forEach(function(scriptTag) {
                    if (scriptTag.src) {
                        var externalScript = document.createElement("script");
                        externalScript.src = scriptTag.src;
                        document.getElementById("content").appendChild(externalScript);
                    } else {eval(scriptTag.innerText); }
                });
            });
    });
    <div id="content"></div>
     <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>

    Example link