0

I have installed a third-party library called Moment.js through bower install --save moment. I have a script named calendar.js placed in scripts folder of my theme. However, when I use moment in my calendar.js it seems the library isn't linked to it. When I move all the code from calendar.js to main.js, everything works fine. The problem is that I need to pass the data into the script by loading a json file and send the data by AJAX so I need to make a separate script, which, in this case, calendar.js. So how do I solve this problem?

Edit: I've enqueued calendar.js in my theme's functions.php like this:

function igs_scripts_styles() {
  wp_enqueue_script( 'calendar', get_template_directory_uri() . '/assets/scripts/calendar.js', array(), false, true );
}
add_action('wp_enqueue_scripts', 'igs_scripts_styles');
fatg
  • 519
  • 7
  • 23

2 Answers2

0

You need to register and enqueue script before using it in wordpress then only wordpress will be able to recognise the script. As of what i can understand the main.js and Moment.js scripts are added properly using wp_enqueue_script which is why they are working fine. I believe if you enqueue the Calendar.js as well that JS file will work fine too.

Johny Santiago
  • 99
  • 1
  • 10
  • I did enqueue the calendar.js, main.js is enqueued in wordpress default setup. Moment.js is installed through bower --save so it should be automatically available: https://roots.io/sage/docs/theme-development-and-building/ – fatg Dec 27 '16 at 14:13
  • can you share your enqueue code because as of what i understand from what you said your calendar.js file is not enqueued properly. – Johny Santiago Dec 27 '16 at 14:24
  • If your Calendar.js file have jquery that you need to add dependency by adding 'jquery' inside array. – Johny Santiago Dec 27 '16 at 14:33
  • Please visit: https://developer.wordpress.org/reference/functions/wp_enqueue_script/ to learn more about enqueue script. You will get the answer there. – Johny Santiago Dec 27 '16 at 14:37
  • I use jQuery in calendar.js without a trouble – fatg Dec 27 '16 at 14:48
  • hey can I ask you a question? How do I control the order of inclusion of assets? I want some libraries to be included after moment.js – fatg Dec 27 '16 at 15:10
-1

It's not really a solution to this problem but a workaround. So I noticed when I moved all the code from calendar.js to main.js it worked all fine. What I did is enqueuing calendar.js with the dependency of main.js (because moment.js is available in main.js). Here's the code:

 wp_enqueue_script( 'calendar', get_template_directory_uri() . '/assets/scripts/calendar.js', ['sage/js'], null, true );
fatg
  • 519
  • 7
  • 23