If you write code on your blog, chances are that you use a syntax highlighter to make the code a bit easier to read. And if you’re on this page, then you likely use the SyntaxHighlighter Evolved plugin.
While this SyntaxHighlighter Evolved works amazing for syntax highlighting, I have noticed that when using this plugin with Jetpack’s infinite scroll, my code snippets weren’t getting highlighted after new posts were added. So, after living with it for the past year or so, I decided to fix the issue.
After doing a bit of searching, I found the following article on Jetpack.com: https://jetpack.com/support/infinite-scroll/#js-events
In that article, they mention how a `post-load JavaScript event is called after posts are fetched and rendered. So, if we combine that with the a call to highlight any code snippets we get this:
/**
* jQuery is likely already enqueued, but let's enqueue here
* to make sure things don't explode.
*/
add_action( 'wp_enqueue_scripts', 'moh_enqueue_jquery' );
function moh_enqueue_jquery() {
wp_enqueue_script( 'jquery' );
}
/**
* This is where the magic happens.
*/
add_action( 'wp_footer', 'moh_trigger_rehighlight', 101 );
function moh_trigger_rehighlight() {
?>
<script>
( function( $ ) {
$( document.body ).on( 'post-load', function () {
if ( 'undefined' !== typeof SyntaxHighlighter ) {
SyntaxHighlighter.highlight();
}
} );
} )( jQuery );
</script>
<?php
}
If you take this example and throw it in a plugin or the functions.php
file for your theme, then all SyntaxHighlighter code snippets should be highlighted every time infinite scroll retrieves a new page. :party:
Leave a Reply