Various

WordPress: Load Scripts on Certain Pages Only

Mike vom Mars Blog beschleunigen boost functions.php javascript jQuery ladezeiten minimieren load on demand nur bei bedarf laden reduce loading time scripte scripts shortcodes speed up stylesheet wordpress wp_enqueue_scripts wp_print_scripts wp_print_styles
 
Estimated reading time: 6 minutes  Viewed 8.692 times

Many plugins are poorly coded. It’s the sad truth. So many of them force WordPress to load their scripts and stylesheets on every single page of your blog, dramatically increasing loading times, bandwidth and HTTP requests. This is especially frustrating for users of mobile devices or with limited data transfer rates. Learn how to dramatically speed up your blog by controlling what scripts and stylesheets are loaded on what page of your blog or under what conditions.

From time to time, you should really check what scripts and styles are loaded into the browser by analysing certain pages of your blog (archive overview, page, single etc.). You’ll eventually be surprised -if not shocked- by the sheer number of crap that is loaded with every page call. Many plugins force their scripts to load with every single page call, even when they are not needed at all!

Generally, you should always be wary after you installed a plugin. There are many bad or inexperienced coders out there that either do not want or do not know how to deliver good work. Personally, I always prefer to code things myself, except for stuff that would really take too much time. But even then, I always check the code of every single plugin and -most important- you should also check if the plugin forces your blog to load it’s javascript or stylesheets into every single page of your blog.

This is the main reason why WordPress tends to slow down after you installed lots of plugins.

Check what scripts and stylesheets are loaded -and where!

If you already know how to do so, feel free to skip this section. Meanwhile, all major browsers include some kind of “style inspector” or “webmaster tools” which are a great help when it comes to analyze a certain web page. We will focus on Firefox here, but Chrome also offers similar tools as well.

With Firefox, press ALT once to show the toolbar (if hidden) and click on ToolsWeb DeveloperNetwork. Start the analysis of the currently shown page by clicking on the speedometer icon. The current page reloads now while the browser analyses what files are loaded into (you could also view the page’s source code -but that’s way more inconvenient).

Once the page analysis is complete, some colored cake diagrams are shown. Now hit the back button on the left side of the tool window to view a list of all loaded files. We are only interested in .css and .js files, so use the JS and CSS buttons on the bottom of the list to filter out all the other stuff. You should now see all the Javascripts (.js) and Stylesheets (.css) that are loaded with the page.

Repeat this procedure on several pages of your blog -in the archives overview, on a single page and so on. If you notice scripts or styles that are loaded on every page, even if they are clearly not needed, you have to get rid of them to speed up your blog and save your users’ valuable bandwidth.

Wordpress wp stylesheets scripts load on demand bei bedarf laden javascript plugin how to wie tutorial shortcode register deregister script style enqueue

Our magic function

The picture above is just an example, the list of loaded stylesheets and javascripts of your blog may look completely different, of course. Generally, there is no need to always load scripts and styles of a plugin that is only related to the content of blog posts, such as lightboxes, spoiler boxes or image sliders. We only need those scripts when viewing a post -and even then, only for post that use the regarding shortcode.

Stylesheets should always be placed in the page header and Javascripts into the footer (at the end) of a page. Therefore, we place a custom function in our functions.php which hooks to the WordPress ‘wp_enqueue_scripts’ action. This means, our custom function will be triggered on every page call, right before the header of the page is sent to the browser.

Then we use our function to

  • de-register (remove) all scripts and styles that are loaded on every page call, but should load on certain pages or under certain conditions instead
  • register and load those scripts and styles again but specify the conditions

As an example situation, let’s assume that we installed the “BBSpoiler” plugin -which does a nice job but unfortunately forces our blog to load it’s javascript and stylesheet files with every single page call. We don’t want that! Since spoiler boxes are used in a post’s content, we only want the plugin’s scripts to be loaded when a page is viewed -and even more: we also want to ensure that the regarding shortcode [ spoiler ] is used in the post. Otherwise, there is no need to load them.

First, we need to find out what names (handles) are used to register the BBSpoiler script and stylesheet. We examine the plugin’s .php (searching for ‘wp_register_style’ and ‘wp_register_script’) and find that both, the javascript and the stylesheet are registered with the name ‘bbspoiler’. That’s all we need.

Now we add a custom function to the functions.php in our theme’s directory:

// ------------------------------------------
// CONTROL THE INCLUSION OF JS AND CSS FILES
// ------------------------------------------
function js_css_control() 
	{
	// GET THE CURRENT POST'S CONTENT
	// TO CHECK FOR CERTAIN SHORTCODES:
	global $wp_query;
	$content = $wp_query->post->post_content;

	// URL TO WORDPRESS PLUGIN DIR:
	$pluginDir = plugins_url();

	// URL TO OUR THEME
	// FOR PARENT THEME: get_template_directory_uri()
	// FOR CHILD  THEME: get_stylesheet_directory_uri()
	$themeDir = get_stylesheet_directory_uri();

	// UNREGISTER ALL SCRIPTS AND STYLES HERE THAT SHOULD
	// *NOT* BE LOADED WITH EVERY PAGE CALL ANYMORE:
	wp_deregister_style ( 'bbspoiler' );  
	wp_deregister_script( 'bbspoiler' );  


	// CHECK IF A POST OR PAGE IS CALLED:
	if ( is_singular() ) 
		{
		// DOES THE POST'S CONTENT INCLUDE A CERTAIN SHORTCODE? 
		// IF SO, LOAD THE REGARDING PLUGIN'S JAVASCRIPT AND STYLE:
		if (has_shortcode($content, 'spoiler')) 
			{
			wp_register_style ('bbspoiler', $pluginDir.'/bbspoiler/inc/bbspoiler.css' );
			wp_register_script('bbspoiler', $pluginDir.'/bbspoiler/inc/bbspoiler.js', array(), '', true);  
			wp_enqueue_style  ('bbspoiler');
			wp_enqueue_script ('bbspoiler');
			}
		}


	}
add_action('wp_enqueue_scripts', 'js_css_control');

That’s it. The BBSpoiler plugin’s javascript und stylesheet files are now loaded with posts (or single pages) only, not with every single blog page. And only if the post’s content contains the regarding [ spoiler ] shortcode.

You can add as many stylesheets and scripts to this function, as you need to. The approach is simple: first, we de-register the scripts and styles, then we register them again, but under certain conditions. Some things should be kept in mind when doing so, however:

  • Examine the plugin’s .php file to find the names (handles) used to register the style and script. Those handles are needed to de-register the files and register them again.
  • When registering a script or style again, be sure to specify the correct path (in most cases the plugin folder). Use plugins_url() to get the location of the WordPress plugin directory and append the plugin folder’s name then, for example.
  • Stylesheets should be placed in the page’s head, while scripts are best placed at the end of a page. To place a script at the end of a page, just set the last parameter of wp_register_script to true -see code above. It’s as easy.
  • This function also enables you to move scripts and styles to any other location. Just specify the new location when registering them again.
  • Some plugins do not use shortcodes, such as lightboxes which often automatically hook to picture links in our content. In this case, you have to search the post’s content for certain HTML tags or image tags, wrapped by a link tags that point to the WordPress upload directory. This can be done easily with preg_match() and expressions.

One last thing: there are several tutorials out there which suggest using wp_print_styles or wp_print_scripts to control the inclusion of scripts and stylesheets. Beware! These tutorials are totally outdated since WordPress does not support these functions anymore since a couple of versions. So don’t wonder if those tutorials are not working for you.

You think this article raised lots of questions? Or you're interested into this topic and would like to know more about? Want to express your personal oppinion? Then feel free to drop a comment here.

Mike vom Mars Blog - mike-vom-mars.comAuthor: Mike vom Mars
A couple of years ago, Mike emigrated from his home planet to Earth to study and examine the human species. His findings offer a deep insight into the nature of human beings and their strange society.


 
Editor rating: 4.0 / 5




Recent Comments

  1. I like this blog so much, saved to my bookmarks .

  2. Hello!Very Interesting post! Thank you for such interesting ruoserce!PS: Sorry for my bad english, I'v just started to learn this language See you!Your, Raiul Baztepo

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.