'Never interrupt an enemy making a mistake.' -Napolean Bonaparte

Conditionally Load Javascript and CSS

by Ethan Glover, Tue, Apr 14, 2015 - (Edited) Thu, Oct 13, 2016

Previously I discussed how to display code and math on your website. However, if you also followed my guide on how to create a static header and footer for a custom built website, you may be worried about pagespeed issues.

With things like Google Prettify and MathJax reloading on every page of your site because the code is in your head file, it can slow things down. Your first thought may be to create a unique head file for pages that use Prettify and MathJax. However, there's an easier way.

PHP offers a simple way of doing if statements. For example, you can send a variable to your head file that tells it whether or not to use certain code. Here's what I mean:

<?php if ($gcode == 1): ?>
[Code to use here]
<?php endif ?>

This means if you set the variable gcode as one on your article page, it will display the code you want. If not, it will be ignored entirely, freeing up bandwidth for pagespeed.

On your article page (such as conditionally-load-javacscript-css.php) create the variable you want to use in the head section. You'll recognize this method from my static header and footer article:

Then, in your head file, use the PHP if statement above to conditionally include the code of your choice. This is especially helpful with JavaScripts that may slow down your site:

With this simple addition, when you want to include Google Prettify on a page, just set the gcode variable to 1. For MathJax, set the mjax variable to 1.