Using requireJS within WordPress

I’m setting up a way for me to keep my preferred requireJS way of working and integrate this with WordPress.

The big issue being how then to load jquery. WordPress loads jQuery via wp_enqueue_script which needs to remain that way as some WordPress plugins I regularly use need jquery to be added that way. I don’t then want to load a second version of jQuery within my requireJS setup. So, after some looking around this is what I’ve come up with:

Read More

templates/footer.php

<script>
if (typeof jQuery === 'function') {
    define( 'jquery', function () { return jQuery; } );
}

require(['/assets/js/sample-common.js'], function (common) {
   require(['sample-bootstrapper']);
});
</script>

Which sees if jQuery has already been added to the page, if it has been then it sets it as the module value.

My question is should I then just leave jquery to be in the global namespace, or follow these instructions:

http://requirejs.org/docs/jquery.html#noconflictmap

The problem with the above is I will probably need to include jquery plugins that aren’t AMD compatible, is it worth the effort to make them AMD compatible or another solution I thought about was removing the true from the noConflict declaration which keeps the ‘jQuery’ in the global namespace allowing the plugins to function.

This is less of a question and more of a call for best practice advice. And any would be much appreciated!

Thanks!

Related posts

Leave a Reply

1 comment

  1. WordPress enqueues jQuery because it’s a script, you should do the same for you own scripts because it means WordPress can gracefully handle the dependencies for you. Also note here that WordPress’s bundled jQuery is already loaded in noConflict() mode to prevent plugin conflicts.

    IF you specify jQuery as one of the dependencies of the script then WordPress will add it to any page that adds the script that depends on it – but only if it has not already been loaded (it won’t add it a second time).

    UPDATE: As per @brasofilo comment the get_stylesheet_directory() function searches child and then parent if nothing matching exists in the child. Safe to use get_stylesheet_directory() in both parent and child theme situations.

    Taken from the WP codex and modified: http://codex.wordpress.org/Function_Reference/wp_enqueue_script

    /**
     * Proper way to enqueue scripts and styles
     */
    function theme_name_scripts() {
        wp_enqueue_script( 'script-name', get_template_directory_uri() . '/assets/js/sample-common.js', array( 'jquery' ), '1.0.0', true );
    }
    
    add_action( 'wp_enqueue_scripts', 'theme_name_scripts' );
    

    It’s worth noting here that if your script is in a child theme directory then you should swap out get_template_directory_uri() and replace it with get_stylesheet_directory_uri().