The Wordpress way of loading Javascript files is through wp_enqueue_script. This ensures that no scripts are loaded twice, and it allows for a mechanism to specify dependencies.
I had the following situation:
A plug-in was loading a JS file with wp_enqueue_script, something like this:
function addMyPluginScript() {
wp_register_script('my-js', plugins_url('/my.js', __FILE__, array('jquery'), '1.0', false) );
wp_enqueue_script('my-js');
}
add_action('wp_enqueue_scripts', 'addMyPluginScript');
In my theme's functions.php I had the following:
function load_scripts() {
wp_enqueue_script('jquery');
// ... other scripts
}
add_action('wp_enqueue_scripts', 'load_scripts');
But although I specified the dependency of 'jquery' in the plug-in's code, the plug-in's JS got loaded BEFORE the theme's jQuery. Hmmm...
The solution was a closer look at the add_action function. Usually it is called with 2 parameters, the hook name and the callback function. But there's also a third, optional parameter: priority. It defaults to 10, and Lower numbers correspond with earlier execution, and functions with the same priority are executed in the order in which they were added to the action.
The fix for out problem: Load the functions scripts before anything else:
function load_scripts() {
wp_enqueue_script('jquery');
// ... other scripts
}
add_action('wp_enqueue_scripts', 'load_scripts', 1); // 1 is smaller than the default 10...