Why do so many WordPress plugins load javascript and CSS files when they are not needed? This was the question going through my head tonight as I looked at at least a half dozen code highlighting plugins.
If I install a plugin for a feature that is used in only a small percentage of my blog, why would I want site visitors to download a bunch of stuff they don’t need? The site visitor may have been referred by a search engine for a blog post that doesn’t need the plugin’s resources. Also, why would I want to make my blog slower with the extra HTTP requests? Loading resources for no reason doesn’t make sense.
Especially when using shortcodes, it’s super easy to determine if the current page needs the resources loaded. WordPress is PHP, and if you are writing a WordPress plugin, you know at least a little PHP. In the case of most code highlighter plugins, they check for <pre> tags, not shortcodes. This makes it no more difficult to determine if the plugin should load resources. Consider PHP’s stripos or strpos functions:
<?php /** * This bit of PHP simply checks if there is a * pre tag with class="brush, and loads some css and * javascript if it does. This is not rocket science. */ function pre_tag_check( $posts ) { // Keep track of whether a pre tag is found $found = FALSE; foreach( $posts as $post ) { // Here is where I am using PHP's stripos function if( stripos( $post->post_content, '<pre class="brush' ) !== FALSE ) { // A pre tag was found $found = TRUE; break; } } // If a pre tag was found if( $found == TRUE ) { // Get the path to this plugin's directory $url = plugin_dir_url( __FILE__ ); // Load a CSS file wp_enqueue_style('some_css', $url . 'css/some_css.css'); // Load a javascript file wp_enqueue_script('some_js', $url . 'js/some_js.js'); } } // If this is not one of the admin pages if( ! is_admin() ) { add_action('the_posts', 'pre_tag_check' ); } // End of example code
In the code above, the PHP is simply checking if there is a pre tag with class=”brush. If this exists, it loads some javascript and CSS. If the the tag is not present in the post or posts, then the script and css are not loaded. Unfortunately, there is one little issue with the code shown above. If a post has some highlighted code and it is not visible because of a more tag, the post is still recognized as needing the script and CSS. I’ve solved this problem on my site by using WordPress’s is_single function.
That’s how it’s done, now get to work!
Richard Pratt says:
I like the way you’ve handled this. Thanks for sharing.