Chris Moore

Load Google Code Prettify on WordPress post pages

Picture of old car that says I used to be beautiful

Google's Code Prettify is a handy set of JavaScript and CSS files that will apply colours and formatting to code embedded within an HTML page. It's a helful addition to sites like mine and make code examples easy to share and read. Now while this set of features is available through the plugin Pretty GC Syntax Highlighter.

One of the big problems that WordPress encounters is bloat, too many resources being loaded onto pages that don't require them. For this website, I wanted to only load my code highlighter, Google's Code Prettify on pages that need it, such as my post content type.

Google's Code Prettify is a powerful javascript module and CSS file that allows syntax highlighting of source code snippets within an HTML page. For WordPress it is available through the plugin Pretty GC Syntax Highlighter.

Conditional load in WordPress: Load javascript only on posts in WordPress.

The disadvantage of such a WordPress plugin is: javascript and CSS files are always loaded, even on pages and in posts that have no source code to highlight. A waste of resources! Particularly in a world where websites have to load as fast as possible, and be as small as possible for mobile devices and (Google) SEO.

 function custom_gcp_js() {
   if( is_single() ) {
     echo '
 // Add hook for front-end
 add_action( 'wp_head', 'custom_gcp_js' );