In quite a few modern frameworks, it\’s usual that only required scripts/styles are loaded on the pages that actually need it. In WordPress, most plugins or themes just load all the scripts/styles all over the pages – \”just in case\” –

Well, optimising for pagespeed can give you great ideas. Why not only load scripts that you need on the pages that actually include that functionality.

In the example below, you will see that the external script \”flickity\”, a pretty nice library for sliders is enqueued. Then, afterwards, we executing the \”get_body_class\” function to read out the default classes WordPress adds to the page.

If one of the classes includes \”single-post\” we dequeue the script and enqueue our script for \”smooth-scroll\”.

function my_enqueue_scripts()
{

    wp_enqueue_script(\'flickity\', \'https://npmcdn.com/flickity@2.2.1/dist/flickity.pkgd.min.js\');
   

	$classes = get_body_class();

	if ( in_array(\'single-post\', $classes) ) {
		wp_dequeue_script(\'flickity\');
		wp_enqueue_script(\'smoothscroll\', \'https://cdnjs.cloudflare.com/ajax/libs/jquery-smooth-scroll/2.2.0/jquery.smooth-scroll.min.js\');
	}
}

add_action( \'wp_enqueue_scripts\', \'my_enqueue_scripts\', 15 );

We are never going to use \”flickity\” on the post page, and thereby saving a precious request! 303ms less. Totally worth it.

\"\"

It\’s also possible to enqueue/dequeue based on template. Very helpful if only certain functionality exists on specific templates.

 if (is_page_template(\'page-templates/dictionary.php\')) :
     // for example if there would be a template named dictionary located in the page-templates folder.
  
     wp_enqueue_style(\'dictionary-styles\', get_template_directory_uri() . \'/css/dictionary.css\', array(), 1);
endif;

You can use those methods in custom built themes, but also in prebuilt themes where you want to save up some bytes because usually theme builders don\’t optimise that much.

In a next post I will dive more into how Gutenberg blocks and Avada\’s page builder are allowing you to only enqueue files that are needed for the block that you add to the page.

Leave a Comment

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