In wordpress, i have two scripts enqueued in the functions.php one after another like this:
First enqueue jQuery:
function enqueue_scripts() {
wp_enqueue_script('jquery');
}
add_action('wp_enqueue_scripts', 'enqueue_scripts');
Then the scripts:
add_action('wp_enqueue_scripts', 'enqueue_my_scripts');
function enqueue_my_scripts() {
wp_enqueue_script(
'script1',
get_template_directory_uri() . '/assets/js/script1.js',
array('jquery'), '1.0', true
);
wp_enqueue_script(
'script2',
get_template_directory_uri() . '/assets/js/script2.js',
array('jquery'), '1.0', true
);
}
The content of my script1.js:
jQuery(document).ready(function($) {
function myFunction1() {
// do something
}
});
The content of my script2.js:
jQuery(document).ready(function($) {
myFunction1();
});
Error in console: Uncaught ReferenceError: myFunction1 is not defined in script2.js
I checked the Network tab, the scripts are loaded and are in the right order, no other errors.
I've tried a couple of things, like changing the jQuery of script1.js to plain Javascript and put it in global scope without the document ready function, nothing worked. Why is the function myFunction1 not accessible in my script2.js? How can i resolve the error?
Your function doesn't need to wait that the DOM is fully loaded, so don't use jQuery
ready()event with your function, as it's not needed and don't allow your 2nd script to find the function.The content of script1.js file:
In your 2nd Script, we use the
ready()event method, as it requires to wait that the DOM is fully loaded and safe to be manipulated.The content of script2.js file:
Note:
jQuery(document).ready(function($){andjQuery(function($){are the same.See jQuery
.ready()event documentation