Hi.
What approaches to adjusting my WP website can I make to adjust these .js loads.
I guess the more accurate answer here would be “it depends”.
Basically, if the plugins JS is being properly registered and included in your WP installation, then the answer is “no, no need to edit your plugins’ code”. However, if the JS calls are hardcoded then editing the plugin(s) in question would be the only way.
So, here are a few guidelines that will certainly help you approach your problem:
I. Guidelines
- Take note of all the JS files you wish to load conditionally (instead of in all your pages) with the respective names of the plugins they belong to.
- Search inside each plugin for the code responsible for loading the JS files. Your best bet here is to search for the filename of each JS script.
- In the WP arena, there are 4 ways in which plugin authors go about calling JS scripts: 1. hardcoding or echoing them, 2. Through a function appended to the add_action hook, 3. Registering them through
wp_register_script
and wp_enqueue_script
, 4. Resorting to a PHP class (very rare, so won’t be covering this).
- You would only need to edit plugins that resort to the 1st method. For those that use methods 2 or 3, there is a workaround that does require any editing of plugin files.
II. Dynamic Methods to load JS scripts
Method 2:
Plugins using this method typically append a function to either the head (more common) or the footer of the document. Examples:
Head:
add_action('wp_head', 'function_to_load_my_JS');
Footer:
add_action('wp_footer', 'function_to_load_my_JS');
In both these cases, you can simply unload those functions from your theme’s functions.php
like so:
Head:
remove_action('wp_head', 'function_to_load_my_JS');
Footer:
remove_action('wp_footer', 'function_to_load_my_JS');
Method 3:
This is the recommended method to call JS scripts in WP. You can read about it in these Codex articles: wp_register_script, wp_deregister_script, wp_enqueue_script, wp_dequeue_script.
Basically, for plugins that use this method, you would need to unload them from functions.php
targeting the handle of each one. Example:
function my_unload_plugin_scripts() {
wp_dequeue_script('some_JS_script_handle');
wp_dequeue_script('another_JS_script_handle');
}
add_action('wp_enqueue_scripts', 'my_unload_plugin_scripts');
Conditional Script Calls:
You would need to re-register your scripts but only when loading certain pages, posts, etc. as desired. For this part, you will need to use Conditional_Tags to test whether the webpage being displayed is the home page or a post, a page, and even a specific post or page.
That should put you in the right direction.
Good luck!