Getting code highlighting working on Blogger

One time setup

Click on Theme in your blog settings, click the down arrow on the Customize button and choose Edit HTML.

Find the </head> tag and paste in the following code just above it, so you end up with:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
</head>

Now find the </body> tag and paste in the following code just above it, so you end up with:

<script>
      //<![CDATA[
      let checkHljsInterval;
      
      checkHljsInterval = setInterval(() => {
          const numCodeSnippets = document.querySelectorAll("pre > code")?.length;
          const numHighlighted = document.querySelectorAll("pre > code.hljs")?.length;
          if (numCodeSnippets > 0) {
              if (numCodeSnippets !== numHighlighted) {
                  hljs.highlightAll();
              } else {
                  clearInterval(checkHljsInterval);
              }
          }
      }, 100);
      //]]>
      </script>
</body>

Without this method, highlight.js does try to be clever and add a onDOMContentLoaded event but it seems that Blogger hasn't completely finished rendering by the time that event fires. Originally I used a timeout but it wasn't reliable and it sometimes felt jarring to see the code highlighting added seconds later. I moved to an interval, which isn't perfect (it will keep running if you have no code to highlight) but it does the job.

Adding code highlighting to a post

To add code formatting to a post, switch to HTML view by clicking the leftmost icon in the edit toolbar and wrap any code segments in <pre><code> tags e.g.

<pre><code>const time = new Date();</code></pre>

If you know the language in advance, you can set it explicitly:

<pre><code class="language-js">const time = new Date();</code></pre>

More details at https://highlightjs.org/

It's a shame you have to go into the HTML editor to add the pre and code tags manually. If anyone knows an easier way to add those tags, let me know in the comments.

Changing the default theme

Browse alternative themes here: https://cdnjs.com/libraries/highlight.js/11.9.0

Copy the URL and replace the href in the One Time Setup step above with the newly chosen theme URL.

Comments

Popular posts from this blog

Using PyTorch on Heroku

Problem deploying app to heroku using GitHub Actions