The best practice to enqueue or registering scripts is to use wp_register_script and wp_enqueue_script. Plugins and themes which do not use this functions to add their scripts, should not be used.
The reason is simple: with wp_register_script() we are able to retrieve a lot of informations about registered scripts. Especially if a given source is already registered or not.
I wrote a simple class to test if a source is already registered. The class can deregister the script and register the new script or skip the new script. This class should be a starting point for your own development. It is not for production enviroment!
How do the class work?
The class retrieve an array with the scripts that should be registered. Than it compare the filenames (and only the filenames) of each registered script with the filenames of the scripts that should be registered. If the script/filename isn't already registered, it's handle will be added to an array and will be registered at a later point.
The class can be extended to compare the full path of the script or the version or whatever is needed to decide if the script should be registered or not.
A simple example
$my_scripts = array(
'foo' => array(
'src' => 'external/ressource/foo.js',
'deps' => array( 'jquery' ),
'version' => false,
'in_footer' => true
),
'bar' => array(
'src' => home_url( '/wp-admin/js/common.min.js' ),
'deps' => false,
'version' => false,
'in_footer' => true
),
'jquery' => array(
'src' => '//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js',
'deps' => false,
'version' => '1.8.3',
'in_footer' => true
),
);
$safe_register = new Safe_Registering_Scripts( $my_scripts, true );
global $wp_scripts;
var_dump( $wp_scripts->registered['jquery'] );
At first we define an array with all our scripts to be registered. The class will walk over our scripts and compare if the source is already registered.
- the
foo script will be always registered because the source isn't registered.
- the
bar script will never be registered because it's source is already registered.
- the
jquery script is a special case. There is already a handle called jquery but the second parameter in the class call says that this script source have to be replaced with the new source.
As you can see in the var_dump(), the source of the jquery script was replaced by the class. So if you extend the class and adjust the test (source, js filename, version, enqueued scripts, etc.), it could help to minimize js collisions.