Add JavaScript code in .md file for GitHub Pages

Since markdown is easier and more readable than HTML, a lot of developers are using it for creating simple looking web pages. GitHub Pages is a platform that allows you to write web pages in markdown and publish them on the Web for free. GitHub converts the markdown pages into HTML pages which also contain CSS and JavaScript code. But what if you want to include your own JavaScript code in the pages? For example you would want to use web analytics platform such as Google Analytics and add the tracking code on every .md file. GitHub flavored markdown supports embedding HTML elements, so it's gonna be easy, right? Just put the script tags and commit.

And it works! Almost...

The JavaScript code is executed successfully on the web page, but on GitHub's interface the code is visible and makes the page ugly. You can try to hide it with HTML:

<div style="display: none;">
    <script src="https://example.com/example.js"></script>
    <script>example();</script>
</div>

but it does not work.

When I faced this problem and tried to solve it with CDATA like this:

<div style="display: none;">
    <![CDATA[
        <script src="https://example.com/example.js"></script>
        <script>example();</script>
    ]]>
</div>

And it worked! Almost...

The first script tag is gone, but </script> <script>example();</script> ]]> is still visible. After a lot of unsuccessfully attempts to hide it, I finally found the problem! The markdown parser closes the opening tag <![CDATA[ with > from .com/example.js">. Then I tried:

<div style="display: none;">
    <![CDATA[<script src="https://example.com/example.js">]]>
    <![CDATA[</script>]]>
    <![CDATA[<script>]]>
        example();
    <![CDATA[</script>]]>
</div>
`

but it inserts illegal characters inside the script tags, so it does not work on GitHub Pages and there are still some visible ]]>. Then I tried this:

<div style="display: none">
    <![CDATA[<script src="https://example.com/example.js">
    <!--<![CDATA[--><![CDATA[
    </script>
    <![CDATA[<script>
    <!--<![CDATA[--><![CDATA[
        example();
    // <![CDATA[
    </script><![CDATA[]]>
</div>

And it works!

The JavaScript code is executed successfully on GitHub Pages and the code does not appear on GitHub's interface! It may be unreadable and ugly, but it works!

Did you find this article valuable?

Support Salif Mehmed by becoming a sponsor. Any amount is appreciated!