Search code examples
javascripthtmlgithubsyntax-highlightinghighlight.js

Highlight file contents fetched from GitHub


I cannot get syntax highlighting to work for code fetched from GitHub.

fetch("https://raw.githubusercontent.com/Ayanmullick/test/master/AutomationAcc/test1.ps1")
      .then(response => response.text())
      .then(data => document.getElementById('code').textContent = data)
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.7.0/build/styles/atom-one-dark-reasonable.min.css">
<script src="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.7.0/build/highlight.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/languages/powershell.min.js"></script>
<script>hljs.highlightAll();</script>

<pre>
<code class="pwsh" id="code"> </code> 
</pre>

However, it's working with code in the same file.

<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.7.0/build/styles/atom-one-dark-reasonable.min.css">
<script src="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.7.0/build/highlight.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/languages/powershell.min.js"></script>
<script>hljs.highlightAll();</script>

<pre><code class="pwsh">
    #PowerShell Hello World
   param
(
    [Parameter(Mandatory=$false)]
    [String] $Name = "World"
)

"Hello $Name!"
 </code></pre>

How should one use the code and pre tags together to highlight code fetched from GitHub?


Solution

  • The reason why highlight.js doesn't work with your code, as I have pointed out in my comment, is that you are inserting the code asynchronously into your DOM after highlight.js has already parsed the DOM. As the code is only inserted after the page is loaded, highlight.js will not be able to detect it.

    If you read through their documentation you'll discover that the plugin offers a highlightElement() method (scroll down the "Custom usage" section on their documentation), which allows you to manually highlight an element.

    So the solution is simply invoking hl's.highlightElement() in the callback you use in your .then() chain:

    fetch("https://raw.githubusercontent.com/Ayanmullick/test/master/AutomationAcc/test1.ps1")
      .then(response => response.text())
      .then(data => {
        const codeElement = document.getElementById('code');
        codeElement.textContent = data;
        
        // Manually trigger code highlighting
        hljs.highlightElement(codeElement);
      });
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.7.0/build/styles/atom-one-dark-reasonable.min.css">
    <script src="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.7.0/build/highlight.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/languages/powershell.min.js"></script>
    <pre>
      <code class="pwsh" id="code"> </code> 
    </pre>