rainbow.js doesn't run Rainbow.color(); on startup

842 views Asked by At

I'm using - or maybe I'm trying to use the rainbow.js syntax highlighting library for the code snippets I publish on my blog (Google Blogger). I think I'm using it correctly:

<pre><code data-language="python">
// here goes the code
</code></pre>

And all needed libraries are loaded in HTML HEAD section:

<link href="//cdnjs.cloudflare.com/ajax/libs/rainbow/1.1.8/themes/github.min.css" rel="stylesheet" type="text/css">
<script src="//cdnjs.cloudflare.com/ajax/libs/rainbow/1.1.8/js/rainbow.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/rainbow/1.1.8/js/language/generic.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/rainbow/1.1.8/js/language/python.min.js"></script>
...

An example post I've got problems with is this one. The code is wrapped in pre/code tags and the background is grey - so CSS is supposed to be loaded correctly. But there is no highlighting actually. But when I type the following:

Rainbow.color();

manually in the JavaScript console, colors (syntax highlighting) does appear. I don't know what's wrong, can anybody give me a hint?


edit:

I have added the following right before :

<script language='javascript' type='text/javascript'>
  window.onload=function(){ Rainbow.color(); };
  Rainbow.color();
</script>

Unfortunately, neither onload nor manual Rainbow.color(); works...

2

There are 2 answers

0
jan199674 On

Im using 'window.history' as a single page application (SPA) to load pages into index.php and had the same problem - rainbow.js doesnt color code. But if i open the page containing code directly in the browser it works.

Adding this at the end of each page after calling rainbow.js made it work when using 'window.history' - could be the same issue on a blog:

<script src="/scripts/rainbow-custom.min.js"></script>
<script>
    setTimeout(Rainbow.color, 1000);
</script> 
0
Álvaro González On

You already have all the pieces. From the documentation:

Rainbow.color

This method is called to highlight all the blocks on the page on load. If you would like to highlight stuff that is not in the DOM you can call it on its own. There are three ways to use it.

One option is adding new code blocks to the DOM and then calling the method again:

// alone
Rainbow.color();

// or with a call back
Rainbow.color(function() {
    console.log('the new blocks are now highlighted!');
});

When you execute scripts in <head> there's no <body> yet.