Helper Wordpress

Helper Wordpress

Wordpress can be fast. Very fast. Really :)

Prevent duplicate JavaScript WordPress via Single Load ONly.

Prevent duplicate JavaScript WordPress via Single Load ONly.

In this post, I want to talk about a common problem with WordPress themes and plugins: how to prevent duplicate JavaScript in WordPress. I’ll also show how this can be solved with the simple approach.

When a javascript is loaded multiple times, it gets executed multiple times. That not only affects performance but can also cause unwanted side effects. For example, if the script attaches a click event to an element, that action may fire several times for a single click.

This is why WordPress developers recommend using the wp_enqueue_script() function. It makes sure a script is only added if it hasn’t already been included. In theory, you can call it several times and the script will only appear once.

But in practice, things aren’t always so smooth. I’ve often seen sites that still load the same script more than once. Why does this happen? There are several reasons, but the three most common are these:

Causes of JavaScript duplication

1 – Direct inclusion inside head tags
Many site owners just follow the documentation for a script and insert it manually.
Almost every tutorial says something like “Insert the <script> tag between <head> and </head>)”.
From the script author’s perspective, that’s fine — their guide is written for any site, not specifically for WordPress. But in WordPress this often means the script gets included multiple times.

2 – Poor-quality or outdated themes and plugins
I’ve seen old or badly coded themes and plugins where JavaScript is added with something like:
echo ‘<script> … </script>’;
This is especially common in templates downloaded from outside the official WP repository.

3 – Different handles in wp_enqueue_script()
The first parameter of the wp_enqueue_script function is $handle, and it must be unique.
For example, suppose you have two plugins that both use Fancybox. Each author correctly calls wp_enqueue_script(), but they use different handles:

wp_enqueue_script (
	'plugin_1_script', 
	plugins_url ('/assets/fancybox/js/fancybox.js', __FILE__), 
	array ('jquery'), 
	'2.0', 
	true
);

and

wp_enqueue_script (
	'plugin_2_script', 
	plugins_url ('/assets/fancybox/js/fancybox.min.js', __FILE__), 
	array ('jquery'), 
	'2.0', 
	true
);

Both plugins are “doing it right,” but WordPress doesn’t know they refer to the same script. As a result, Fancybox gets loaded twice. (And the same issue can happen with any popular library.)

So how do we prevent duplicate JavaScript in WordPress?

The solution: Single Load ONly (SLON):

One option is to give the site owner control. Let them decide whether a script should be loaded or not. If they notice in the page source that a library is already being added elsewhere, they should have a way to disable duplication.

Here’s how it can work, using Bootstrap as an example:

Add a plugin option like my_plugin_bootstrap_load:

function my_plugin_set_options() {
	add_option('my_plugin_bootstrap_load', 1);
}

Provide a settings field to change that option:

function my_plugin_options_page() {
	$myPluginBootstrapLoad = get_option('my_plugin_bootstrap_load');

	if ( ! isset( $_REQUEST['myPluginBootstrapLoad'] ) )
		$_REQUEST['myPluginBootstrapLoad'] = false;

	if ( isset ($_REQUEST['settingsUpdated']) && $_REQUEST['settingsUpdated'] == true ){
		update_option('my_plugin_bootstrap_load', $_REQUEST['myPluginBootstrapLoad']);
	?>
	<div class="updated"><p><strong> <?php _e('Your settings are saved', 'my_plugin'); ?></strong></p></div>
	<?php
}
?>
<form method="post" action="<? echo $_SERVER['REQUEST_URI'];?>">
	<?php
	if ($_REQUEST['settingsUpdated']){
		$selectBootstrapLoad = $_REQUEST['myPluginBootstrapLoad'];
	} else {
		$selectBootstrapLoad = $myPluginBootstrapLoad;
	}
	?>
	<select name="myPluginBootstrapLoad">
		<option value="1" <?php echo ($selectBootstrapLoad == 1) ? 'selected' : false ;?>><?php echo __('Load Bootstrap from the site', 'my_plugin'); ?></option>
		<option value="0" <?php echo ($selectBootstrapLoad == 0) ? 'selected' : false ;?>><?php echo __('Don\'t load Bootstrap', 'my_plugin'); ?></option>
	</select>

	<input type="submit" name="settingsUpdated" class="button button-primary" value="<?php _e('Save Changes', 'my_plugin') ?>" />

</form>
<?php
}
?>

And finally, enqueue Bootstrap depending on the option’s value:

if (get_option('my_plugin_bootstrap_load') == 1){
	function enqueue_external_files() {
		wp_enqueue_script( 'my-plugin-bootstrap-js', '//netdna.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js', array('jquery'), true); // all the bootstrap javascript goodness
		wp_enqueue_style( 'my-plugin-bootstrap-css', '//netdna.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css' );
	}
add_action('wp_enqueue_scripts', 'enqueue_external_files');
}

If you have questions or suggestions about prevent duplicate JavaScript in WordPress, I’d be happy to hear your feedback.

And finally, I propose calling this approach SLON. In Ukrainian, slon means elephant — but here it also stands for Single Load ONly.

If the article proved helpful to you, please click on one of the buttons to share it with your friends. Thanks!

Related posts:

Youtube Embed Performance – plugin for WP

Youtube Embed Performance – plugin for WP

Youtube Embed Performance will improve the performance of your initial page load, especially if there are two or more videos embedded on the same page. I think, it’s [...]
What’s New in WordPress 5.1

What’s New in WordPress 5.1

WordPress 5.1 available on February 21, 2019. It have name “Betty” in honoring American jazz singer Betty Carter. WordPress 5.0 had been downloaded more than 35 million times [...]

Leave a Reply

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