1
votes

Hello I am using the jQuery UI accordion on a website with wordpress and I get the error: "Uncaught TypeError: $(...).accordion is not a function"

In my functions.php I load a app.js, where I have bundled the jQuery UI file and other jQuery plugins, with this function: wp_enqueue_script( 'theme-js', get_template_directory_uri() . '/js/app.js', array('jquery'), null, true );

To bundle the app.js file I use webpack.

This is how i include jQuery UI in my main.js in webpack:

var $ = window.jQuery;
var jqueryUi = require("./jquery-ui.min.js");

I already disabled all plugins on my wordpress installation and deleted othe jQuery plugins.

Thank you.

2

2 Answers

2
votes

1- Default Scripts Included and Registered by WordPress
2- You did not add/call/enqueue jQuery UI accordion
wp_enqueue_script('jquery-ui-accordion');
You will maybe need to add/call/enqueue jQuery UI Core wp_enqueue_script('jquery-ui-core');
This is because .accordion()is a jQuery UI effect and not just jQuery !
3- Be sure to wrap your JS with ;
jQuery( document ).ready( function( $ ) { PUT YOU JS HERE });
Final note : are you using node.js ?
If not, what is this require ???
Hope this helps, SYA

1
votes

In your output, it looks like it's probably a load order issue. Tough to say unless you provide your unbundled and bundled output.

Regardless, this is exactly what the WordPress enqueue system is designed for -- dependency management. I would enqueue jQuery UI separately and assign the appropriate dependencies exclusively through WP. This will hopefully prevent issues like this, and also prevent any issues with double including JS files. If you're bundling jQuery UI and someday use a plugin that depends on it, WP might enqueue it, and you'll have two versions loaded on your site. Bad for performance, and a headache to maintain.

If you're worried about performance but using HTTP/2 on your site, loading these scripts separately should no longer be as much of a concern as it used to be, since you can load the through one TCP connection and it's multiplexed.

https://http2.github.io/faq/#what-are-the-key-differences-to-http1x

In short, I see more advantages to separately enqueuing, and fewer with bundling it into your JS.