Having trouble understanding how to properly enque

2019-09-01 05:55发布

问题:

So as recommended, I enqueue my scripts in the function.php file instead of in the head like the following example:

function bok_scripts() {
    wp_enqueue_script( 'custom', get_template_directory_uri() . '/js/custom.js' );
}
add_action( 'wp_enqueue_scripts', 'bok_scripts' );

The problem is that this JavaScript won't work unless I add jQuery to the head using the usual:

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

The problem I always run into, though, is that WordPress automatically loads a version of jQuery using the wp_head(); from the wp-admin/includes directory. Because the jQuery is getting loaded 2x, it breaks some of the code. For instance the following will throw a 'This is not a function ($)' error:

$(window).load(function(){
    $('#modal-notices').modal('show');
});

Does anyone know how to overcome this? I've tried a bunch of stuff, but all that seems to work is deleting the jQuery from the wp-admin/includes directory. Obviously, though, that isn't a proper fix.

回答1:

The first thing you need to do is declare jQuery as a dependency of your script so that WordPress knows to load it.

To do that change:

wp_enqueue_script( 'custom', get_template_directory_uri() . '/js/custom.js' );

To:

wp_enqueue_script( 'custom', get_template_directory_uri() . '/js/custom.js', array( 'jquery' ) );

There's a second issue you're facing and that's jQuery in WordPress loads in noConflict mode. This means the global '$' shortcut is no longer available. Here's some more information: http://codex.wordpress.org/Function_Reference/wp_enqueue_script#jQuery_noConflict_Wrappers

To get your script working change:

$(window).load(function(){
    $('#modal-notices').modal('show');
});

To:

(function($) {
    $(window).load(function(){
        $('#modal-notices').modal('show');
    });
})(jQuery);

Finally be sure to remove any jQuery scripts you've added directly to the header/footer instead of enqueueing.